Team Ai
Apppublic

oex2003/evolution-api

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
main.ts159 linesDownload Raw Back to src
1// Import this first from sentry instrument!2import '@utils/instrumentSentry';3 4// Now import other modules5import { ProviderFiles } from '@api/provider/sessions';6import { PrismaRepository } from '@api/repository/repository.service';7import { HttpStatus, router } from '@api/routes/index.router';8import { eventManager, waMonitor } from '@api/server.module';9import { Auth, configService, Cors, HttpServer, ProviderSession, Webhook } from '@config/env.config';10import { onUnexpectedError } from '@config/error.config';11import { Logger } from '@config/logger.config';12import { ROOT_DIR } from '@config/path.config';13import * as Sentry from '@sentry/node';14import { ServerUP } from '@utils/server-up';15import axios from 'axios';16import compression from 'compression';17import cors from 'cors';18import express, { json, NextFunction, Request, Response, urlencoded } from 'express';19import { join } from 'path';20 21function initWA() {22  waMonitor.loadInstance();23}24 25async function bootstrap() {26  const logger = new Logger('SERVER');27  const app = express();28 29  let providerFiles: ProviderFiles = null;30  if (configService.get<ProviderSession>('PROVIDER').ENABLED) {31    providerFiles = new ProviderFiles(configService);32    await providerFiles.onModuleInit();33    logger.info('Provider:Files - ON');34  }35 36  const prismaRepository = new PrismaRepository(configService);37  await prismaRepository.onModuleInit();38 39  app.use(40    cors({41      origin(requestOrigin, callback) {42        const { ORIGIN } = configService.get<Cors>('CORS');43        if (ORIGIN.includes('*')) {44          return callback(null, true);45        }46        if (ORIGIN.indexOf(requestOrigin) !== -1) {47          return callback(null, true);48        }49        return callback(new Error('Not allowed by CORS'));50      },51      methods: [...configService.get<Cors>('CORS').METHODS],52      credentials: configService.get<Cors>('CORS').CREDENTIALS,53    }),54    urlencoded({ extended: true, limit: '136mb' }),55    json({ limit: '136mb' }),56    compression(),57  );58 59  app.set('view engine', 'hbs');60  app.set('views', join(ROOT_DIR, 'views'));61  app.use(express.static(join(ROOT_DIR, 'public')));62 63  app.use('/store', express.static(join(ROOT_DIR, 'store')));64 65  app.use('/', router);66 67  app.use(68    (err: Error, req: Request, res: Response, next: NextFunction) => {69      if (err) {70        const webhook = configService.get<Webhook>('WEBHOOK');71 72        if (webhook.EVENTS.ERRORS_WEBHOOK && webhook.EVENTS.ERRORS_WEBHOOK != '' && webhook.EVENTS.ERRORS) {73          const tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds74          const localISOTime = new Date(Date.now() - tzoffset).toISOString();75          const now = localISOTime;76          const globalApiKey = configService.get<Auth>('AUTHENTICATION').API_KEY.KEY;77          const serverUrl = configService.get<HttpServer>('SERVER').URL;78 79          const errorData = {80            event: 'error',81            data: {82              error: err['error'] || 'Internal Server Error',83              message: err['message'] || 'Internal Server Error',84              status: err['status'] || 500,85              response: {86                message: err['message'] || 'Internal Server Error',87              },88            },89            date_time: now,90            api_key: globalApiKey,91            server_url: serverUrl,92          };93 94          logger.error(errorData);95 96          const baseURL = webhook.EVENTS.ERRORS_WEBHOOK;97          const httpService = axios.create({ baseURL });98 99          httpService.post('', errorData);100        }101 102        return res.status(err['status'] || 500).json({103          status: err['status'] || 500,104          error: err['error'] || 'Internal Server Error',105          response: {106            message: err['message'] || 'Internal Server Error',107          },108        });109      }110 111      next();112    },113    (req: Request, res: Response, next: NextFunction) => {114      const { method, url } = req;115 116      res.status(HttpStatus.NOT_FOUND).json({117        status: HttpStatus.NOT_FOUND,118        error: 'Not Found',119        response: {120          message: [`Cannot ${method.toUpperCase()} ${url}`],121        },122      });123 124      next();125    },126  );127 128  const httpServer = configService.get<HttpServer>('SERVER');129 130  ServerUP.app = app;131  let server = ServerUP[httpServer.TYPE];132 133  if (server === null) {134    logger.warn('SSL cert load failed — falling back to HTTP.');135    logger.info("Ensure 'SSL_CONF_PRIVKEY' and 'SSL_CONF_FULLCHAIN' env vars point to valid certificate files.");136 137    httpServer.TYPE = 'http';138    server = ServerUP[httpServer.TYPE];139  }140 141  eventManager.init(server);142 143  if (process.env.SENTRY_DSN) {144    logger.info('Sentry - ON');145 146    // Add this after all routes,147    // but before any and other error-handling middlewares are defined148    Sentry.setupExpressErrorHandler(app);149  }150 151  server.listen(httpServer.PORT, () => logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT));152 153  initWA();154 155  onUnexpectedError();156}157 158bootstrap();159