From 4565120b2ab01f8c80761c670134df25bbc61fdd Mon Sep 17 00:00:00 2001 From: isra el Date: Sat, 2 Mar 2024 21:24:17 +0300 Subject: [PATCH] feat(api): add gateway stats endpoint --- api/src/gateway/gateway.controller.ts | 7 +++++++ api/src/gateway/gateway.service.ts | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/api/src/gateway/gateway.controller.ts b/api/src/gateway/gateway.controller.ts index b5d92f0..2d35dbe 100644 --- a/api/src/gateway/gateway.controller.ts +++ b/api/src/gateway/gateway.controller.ts @@ -21,6 +21,13 @@ import { CanModifyDevice } from './guards/can-modify-device.guard' export class GatewayController { constructor(private readonly gatewayService: GatewayService) {} + @UseGuards(AuthGuard) + @Get('/stats') + async getStats(@Request() req) { + const data = await this.gatewayService.getStatsForUser(req.user) + return { data } + } + @UseGuards(AuthGuard) @ApiOperation({ summary: 'Register device' }) @ApiQuery({ diff --git a/api/src/gateway/gateway.service.ts b/api/src/gateway/gateway.service.ts index c1cdfd7..eb6caae 100644 --- a/api/src/gateway/gateway.service.ts +++ b/api/src/gateway/gateway.service.ts @@ -5,10 +5,12 @@ import { Model } from 'mongoose' import * as firebaseAdmin from 'firebase-admin' import { RegisterDeviceInputDTO, SendSMSInputDTO } from './gateway.dto' import { User } from '../users/schemas/user.schema' +import { AuthService } from 'src/auth/auth.service' @Injectable() export class GatewayService { constructor( @InjectModel(Device.name) private deviceModel: Model, + private authService: AuthService, ) {} async registerDevice( @@ -111,4 +113,22 @@ export class GatewayService { ) } } + + async getStatsForUser(user: User) { + const devices = await this.deviceModel.find({ user: user._id }) + const apiKeys = await this.authService.getUserApiKeys(user) + + const totalSMSCount = devices.reduce((acc, device) => { + return acc + (device.sentSMSCount || 0) + }, 0) + + const totalDeviceCount = devices.length + const totalApiKeyCount = apiKeys.length + + return { + totalSMSCount, + totalDeviceCount, + totalApiKeyCount, + } + } }