universo-platform-3d

Форк
0
115 строк · 4.1 Кб
1
require('dotenv').config()
2
import { ValidationPipe } from '@nestjs/common'
3
import { NestFactory } from '@nestjs/core'
4
import { NestExpressApplication } from '@nestjs/platform-express'
5
import { WsAdapter } from '@nestjs/platform-ws'
6
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
7
import { SentryService } from '@ntegral/nestjs-sentry'
8
import {
9
  WinstonModule,
10
  utilities as nestWinstonModuleUtilities
11
} from 'nest-winston'
12
import * as os from 'os'
13
import * as winston from 'winston'
14
import { AppModule } from './app.module'
15
import AllExceptionsFilter from './error-handling/all-exceptions.filter'
16
import metadata from './metadata'
17
import { NODE_ENV } from './util/node-env.enum'
18

19
async function bootstrapMirrorWebServer() {
20
  console.log('Starting mirror-web-server')
21

22
  const version = require('../package.json').version // eslint-disable-line @typescript-eslint/no-var-requires
23
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
24
    // 2023-07-13 23:04:10: with Winston, there's weirdness with the test setup where the logs get suppressed in tests. This obviously isnt desirable when running tests, so I've added this ternary to not use Winston in tests.
25
    logger:
26
      process.env.NODE_ENV === NODE_ENV.TEST
27
        ? undefined
28
        : WinstonModule.createLogger({
29
            transports: [
30
              new winston.transports.Console({
31
                format: winston.format.combine(
32
                  winston.format.timestamp(),
33
                  winston.format.ms(),
34
                  nestWinstonModuleUtilities.format.nestLike('mirror-server', {
35
                    colors: true,
36
                    prettyPrint: true
37
                  })
38
                ),
39
                level: process.env.NODE_ENV === NODE_ENV.TEST ? 'debug' : 'info'
40
              })
41
              // other transports...
42
            ]
43
            // other options
44
          }),
45
    rawBody: true //**This is required for stripe webhook
46
  })
47

48
  /**
49
   * Swagger
50
   */
51
  await SwaggerModule.loadPluginMetadata(metadata)
52
  const config = new DocumentBuilder()
53
    .setTitle('Mirror Web Server')
54
    .setDescription('Mirror Web Server API')
55
    .setVersion(version)
56
    .build()
57
  const document = SwaggerModule.createDocument(app, config)
58
  // For the publicly-exposed docs, append random string of characters appended to "hide" it
59
  SwaggerModule.setup(
60
    'api-bejmnvpnugdasdfjkasdjfkasjdfjksdfasdui9823hui23',
61
    app,
62
    document
63
  )
64
  // If on localhost in dev, then still allow for http://localhost:9000/api
65
  if (
66
    os.hostname().includes('local') &&
67
    process.env.NODE_ENV !== 'production' &&
68
    !process.env.K_REVISION // This is truthy if on GCP cloud run
69
  ) {
70
    SwaggerModule.setup('api', app, document)
71
  }
72

73
  // default
74
  app.enableCors({
75
    // cors has to be here
76
    origin: '*' // TODO change to only the frontend
77
  })
78
  app.useWebSocketAdapter(new WsAdapter(app))
79

80
  // asset storage driver env validation
81
  if (
82
    process.env.ASSET_STORAGE_DRIVER === 'GCP' &&
83
    !process.env.GCS_BUCKET_PUBLIC
84
  ) {
85
    throw new Error('GCS_BUCKET_PUBLIC is required when using GCP storage')
86
  }
87

88
  if (
89
    (!process.env.ASSET_STORAGE_DRIVER ||
90
      process.env.ASSET_STORAGE_DRIVER === 'LOCAL') &&
91
    !process.env.ASSET_STORAGE_URL
92
  ) {
93
    throw new Error('ASSET_STORAGE_URL is required when using LOCAL storage')
94
  }
95

96
  // Important: This *only* sets up validation pipes for HTTP handlers, NOT Websockets. See the notice here: https://docs.nestjs.com/pipes#global-scoped-pipes
97
  app.useGlobalPipes(
98
    new ValidationPipe({
99
      transform: true,
100
      // whitelist: true, // Do NOT remove whitelist: true. This is a big security risk if it's not there since we pass dtos from the controllers directly into Mongo
101
      enableDebugMessages:
102
        process.env.NODE_ENV === NODE_ENV.DEVELOPMENT ? true : false
103
    })
104
  )
105

106
  // Add global exception filter for Sentry to handle 500 errors
107
  const sentryService = app.get<SentryService>(SentryService)
108
  app.useGlobalFilters(new AllExceptionsFilter(sentryService))
109

110
  const port = process.env.PORT || 9000
111
  console.log(`Running on port ${port}`)
112
  await app.listen(port)
113
}
114

115
bootstrapMirrorWebServer()
116

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.