📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
implemented Alerts CRUD
Blue Moused6a20b07f794
diff --git a/src/alert/alert.controller.ts b/src/alert/alert.controller.tsindex b1195c9a7..b1089f5e8 100644--- a/src/alert/alert.controller.ts+++ b/src/alert/alert.controller.ts@@ -1,16 +1,110 @@import {- Controller,+ Controller, Get, Put, Delete, UseGuards, Query, Param, Body, NotFoundException,} from '@nestjs/common'-import { ApiTags } from '@nestjs/swagger'+import { In } from 'typeorm'+import { ApiTags, ApiResponse } from '@nestjs/swagger'import { AlertService } from './alert.service'+import { SelfhostedGuard } from '../common/guards/selfhosted.guard'+import { RolesGuard } from '../common/guards/roles.guard'+import * as _isEmpty from 'lodash/isEmpty'+import * as _map from 'lodash/map'+import * as _omit from 'lodash/omit'+import { UserService } from 'src/user/user.service'+import { ProjectService } from 'src/project/project.service'+import { AppLoggerService } from 'src/logger/logger.service'+import { CurrentUserId } from '../common/decorators/current-user-id.decorator'+import { Roles } from '../common/decorators/roles.decorator'+import { UserType } from 'src/user/entities/user.entity'+import { Alert } from './entity/alert.entity'+import { AlertDTO } from './dto/alert.dto'@ApiTags('Alert')@Controller('alert')export class AlertController {constructor(private readonly alertService: AlertService,- ) {}+ private readonly projectService: ProjectService,+ private readonly logger: AppLoggerService,+ private readonly userService: UserService,+ ) { }- // TODO: ADD ENDPOINTS TO CREATE / UPDATE / DELETE ALERTS+ @Get('/')+ @UseGuards(SelfhostedGuard)+ @UseGuards(RolesGuard)+ @Roles(UserType.ADMIN, UserType.CUSTOMER)+ @ApiResponse({ status: 200, type: Alert })+ async getAllAlerts(+ @CurrentUserId() userId: string,+ @Query('take') take: number | undefined,+ @Query('skip') skip: number | undefined,+ ) {+ this.logger.log({ userId, take, skip }, 'GET /alert')++ const projects = await this.projectService.findWhere({ admin: userId })++ if (_isEmpty(projects)) {+ return []+ }++ const pids = _map(projects, (project) => project.id)++ return this.alertService.paginate({ take, skip }, { project: In(pids) })+ }++ @Put('/:id')+ @UseGuards(SelfhostedGuard)+ @UseGuards(RolesGuard)+ @Roles(UserType.ADMIN, UserType.CUSTOMER)+ @ApiResponse({ status: 200, type: Alert })+ async updateAlert(+ @Param('id') id: string,+ @Body() alertDTO: AlertDTO,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ id, uid }, 'PUT /alert/:id')++ let alert = await this.alertService.findOneWithRelations(id)++ if (_isEmpty(alert)) {+ throw new NotFoundException()+ }++ const user = await this.userService.findOne(uid)++ this.projectService.allowedToManage(alert.project, uid, user.roles, 'You are not allowed to manage this alert')++ alert = {+ ...alert,+ ...alertDTO,+ }++ await this.alertService.update(id, _omit(alert, ['project', 'lastTriggered']))++ return alert+ }++ @Delete('/:id')+ @UseGuards(SelfhostedGuard)+ @UseGuards(RolesGuard)+ @Roles(UserType.ADMIN, UserType.CUSTOMER)+ @ApiResponse({ status: 204, description: 'Empty body' })+ async deleteAlert(+ @Param('id') id: string,+ @CurrentUserId() uid: string,+ ) {+ this.logger.log({ id, uid }, 'DELETE /alert/:id')++ let alert = await this.alertService.findOneWithRelations(id)++ if (_isEmpty(alert)) {+ throw new NotFoundException()+ }++ const user = await this.userService.findOne(uid)++ this.projectService.allowedToManage(alert.project, uid, user.roles, 'You are not allowed to manage this alert')++ await this.alertService.delete(id)+ }}diff --git a/src/alert/alert.module.ts b/src/alert/alert.module.tsindex acc21cf0e..aaa598d49 100644--- a/src/alert/alert.module.ts+++ b/src/alert/alert.module.ts@@ -3,11 +3,17 @@ import { TypeOrmModule } from '@nestjs/typeorm'import { Alert } from './entity/alert.entity'import { AlertService } from './alert.service'+import { ProjectModule } from 'src/project/project.module'+import { AppLoggerModule } from 'src/logger/logger.module'+import { UserModule } from 'src/user/user.module'import { AlertController } from './alert.controller'@Module({imports: [TypeOrmModule.forFeature([Alert]),+ ProjectModule,+ AppLoggerModule,+ UserModule,],providers: [AlertService],exports: [AlertService],diff --git a/src/alert/alert.service.ts b/src/alert/alert.service.tsindex 3b1248d09..9c3015c14 100644--- a/src/alert/alert.service.ts+++ b/src/alert/alert.service.ts@@ -5,6 +5,7 @@ import { InjectRepository } from '@nestjs/typeorm'import { Repository } from 'typeorm'import { Alert } from './entity/alert.entity'import { AlertDTO } from './dto/alert.dto'+import { Pagination, PaginationOptionsInterface } from 'src/common/pagination'@Injectable()export class AlertService {@@ -13,6 +14,27 @@ export class AlertService {private alertsReporsitory: Repository<Alert>,) {}+ async paginate(+ options: PaginationOptionsInterface,+ where: Record<string, unknown> | undefined,+ relations?: Array<string>,+ ): Promise<Pagination<Alert>> {+ const [results, total] = await this.alertsReporsitory.findAndCount({+ take: options.take || 100,+ skip: options.skip || 0,+ where,+ order: {+ name: 'ASC',+ },+ relations,+ })++ return new Pagination<Alert>({+ results,+ total,+ })+ }+findOneWithRelations(id: string): Promise<Alert | null> {return this.alertsReporsitory.findOne(id, { relations: ['project'] })}diff --git a/src/project/project.service.ts b/src/project/project.service.tsindex 54a10acf2..525b9e316 100644--- a/src/project/project.service.ts+++ b/src/project/project.service.ts@@ -217,6 +217,7 @@ export class ProjectService {project: Project,uid: string,roles: Array<UserType> = [],+ message: string = 'You are not allowed to manage this project'): void {if (uid === project.admin?.id ||@@ -228,7 +229,7 @@ export class ProjectService {) {return} else {- throw new ForbiddenException('You are not allowed to manage this project')+ throw new ForbiddenException(message)}}