Team Ai
Apppublic

oex2003/evolution-api

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
instance.guard.ts56 linesDownload Raw Back to guards
1import { InstanceDto } from '@api/dto/instance.dto';2import { cache, prismaRepository, waMonitor } from '@api/server.module';3import { CacheConf, configService } from '@config/env.config';4import { BadRequestException, ForbiddenException, InternalServerErrorException, NotFoundException } from '@exceptions';5import { NextFunction, Request, Response } from 'express';6 7async function getInstance(instanceName: string) {8  try {9    const cacheConf = configService.get<CacheConf>('CACHE');10 11    const exists = !!waMonitor.waInstances[instanceName];12 13    if (cacheConf.REDIS.ENABLED && cacheConf.REDIS.SAVE_INSTANCES) {14      const keyExists = await cache.has(instanceName);15 16      return exists || keyExists;17    }18 19    return exists || (await prismaRepository.instance.findMany({ where: { name: instanceName } })).length > 0;20  } catch (error) {21    throw new InternalServerErrorException(error?.toString());22  }23}24 25export async function instanceExistsGuard(req: Request, _: Response, next: NextFunction) {26  if (req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) {27    return next();28  }29 30  const param = req.params as unknown as InstanceDto;31  if (!param?.instanceName) {32    throw new BadRequestException('"instanceName" not provided.');33  }34 35  if (!(await getInstance(param.instanceName))) {36    throw new NotFoundException(`The "${param.instanceName}" instance does not exist`);37  }38 39  next();40}41 42export async function instanceLoggedGuard(req: Request, _: Response, next: NextFunction) {43  if (req.originalUrl.includes('/instance/create')) {44    const instance = req.body as InstanceDto;45    if (await getInstance(instance.instanceName)) {46      throw new ForbiddenException(`This name "${instance.instanceName}" is already in use.`);47    }48 49    if (waMonitor.waInstances[instance.instanceName]) {50      delete waMonitor.waInstances[instance.instanceName];51    }52  }53 54  next();55}56