From 03b2ec5f66e3881c7e026ca2df116e67da3382aa Mon Sep 17 00:00:00 2001 From: janderedev Date: Wed, 23 Mar 2022 20:13:43 +0100 Subject: [PATCH] add /stats API endpoint --- api/src/index.ts | 1 + api/src/routes/stats.ts | 24 ++++++++++++++++++++++++ bot/src/bot/modules/api_communication.ts | 5 +++++ 3 files changed, 30 insertions(+) create mode 100644 api/src/routes/stats.ts diff --git a/api/src/index.ts b/api/src/index.ts index dfffa4e..f064572 100644 --- a/api/src/index.ts +++ b/api/src/index.ts @@ -27,6 +27,7 @@ export { logger, app, db, PORT, SESSION_LIFETIME } import('./routes/internal/ws'), import('./routes/root'), + import('./routes/stats'), import('./routes/login'), import('./routes/dash/servers'), import('./routes/dash/server'), diff --git a/api/src/routes/stats.ts b/api/src/routes/stats.ts new file mode 100644 index 0000000..d43fab5 --- /dev/null +++ b/api/src/routes/stats.ts @@ -0,0 +1,24 @@ +import { app, logger } from '..'; +import { Request, Response } from 'express'; +import { botReq } from './internal/ws'; + +let SERVER_COUNT = 0; + +const fetchStats = async () => { + try { + const res = await botReq('stats'); + if (!res.success) return logger.warn(`Failed to fetch bot stats: ${res.statusCode} / ${res.error}`); + if (res.servers) SERVER_COUNT = Number(res.servers); + } catch(e) { + console.error(e); + } +} + +fetchStats(); +setInterval(() => fetchStats(), 10000); + +app.get('/stats', async (req: Request, res: Response) => { + res.send({ + servers: SERVER_COUNT, + }); +}); \ No newline at end of file diff --git a/bot/src/bot/modules/api_communication.ts b/bot/src/bot/modules/api_communication.ts index c9fcc9c..c6ef4ed 100644 --- a/bot/src/bot/modules/api_communication.ts +++ b/bot/src/bot/modules/api_communication.ts @@ -136,6 +136,11 @@ wsEvents.on('req:requestLogin', async (data: any, cb: (data: WSResponse) => void } }); +wsEvents.on('req:stats', async (_data: any, cb: (data: { servers: number }) => void) => { + const servers = bot.servers.size; + cb({ servers }); +}); + export { wsEvents, wsSend, WSResponse } import('./api/servers');