Skip to content

Commit

Permalink
feat: add rest APIs for agent info to the hub
Browse files Browse the repository at this point in the history
  • Loading branch information
Dinko Bajric committed May 10, 2022
1 parent c0ce4d5 commit a150a86
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
16 changes: 13 additions & 3 deletions packages/@best/agent-hub/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,20 @@ export function run() {
const hubConfig = getHubConfig();

const app = express();
serveFrontend(app);
const server = http.createServer(app);
const agent = new Hub(server, hubConfig);
observeAgent(server, agent);
const hub = new Hub(server, hubConfig);

app.get("/api/agents/:agentId", (req, res) => {
const { agentId } = req.params;
res.json(hub.getAgent(agentId));
});

app.get("/api/agents", (req, res) => {
res.json(hub.getAgents());
});

serveFrontend(app);
observeAgent(server, hub);

server.listen(PORT);
process.stdout.write(`Best Hub listening in port ${PORT}...\n`);
Expand Down
29 changes: 29 additions & 0 deletions packages/@best/agent-hub/src/hub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,4 +244,33 @@ export class Hub extends EventEmitter {
activeClients
};
}

/**
* Gets a list of all agents connected to the hub
* @returns an array with connected agents
*/
getAgents() {
return Array.from(this.connectedAgents).map(agent => agent.getState());
}

/**
* Gets agent info based on specified identifier.
* @param id a unique identifier of an agent
* @returns agent info
*/
getAgent(id: string) {
const agents = Array.from(this.connectedAgents)
.filter((agent) => agent.getId() === id)
.map(agent => agent.getState());

if (!agents || agents.length === 0) {
return;
}

if (agents.length > 1) {
throw new Error(`Multiple agents with the same ID found. ID: ${id}`);
}

return agents[0];
}
}

0 comments on commit a150a86

Please sign in to comment.