index.ts 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. import sequelize from './db'
  2. import { Sequelize } from 'sequelize-typescript'
  3. import express, { Request } from 'express'
  4. import path from 'path'
  5. import cookieParser from 'cookie-parser'
  6. import logger from 'morgan'
  7. import helmet from 'helmet'
  8. import { Controller } from './controllers'
  9. import errorMiddleware from './middleware/error.middleware'
  10. import setHeaderMiddleware from './middleware/setHeaders.middleware'
  11. import { Server } from 'http'
  12. import 'moment-timezone'
  13. // import { Constant } from './db/models'
  14. // import { defaultSolanaHelper } from './utils/SolanaHelper'
  15. const deleteRequestBodySaver = function (
  16. req: Request,
  17. res: any,
  18. buf: any,
  19. encoding: any
  20. ): void {
  21. if (buf?.length && req.method.toLocaleUpperCase() === 'DELETE') {
  22. try {
  23. const str = buf.toString(encoding || 'utf8')
  24. req.body = JSON.parse(str)
  25. } catch (error) {}
  26. }
  27. }
  28. export interface APPOtions {
  29. port: number
  30. controllers: Controller[]
  31. tgBotToken: string
  32. }
  33. const defaultOptions: APPOtions = {
  34. port: 9099,
  35. controllers: [],
  36. tgBotToken: process.env.TG_BOT_TOKEN ?? '',
  37. }
  38. export default class APP {
  39. private readonly option
  40. public app: express.Application
  41. private db?: Sequelize
  42. private server?: Server
  43. constructor(options: Partial<APPOtions>) {
  44. this.option = {
  45. ...defaultOptions,
  46. ...options,
  47. }
  48. this.app = express()
  49. process.once('SIGINT', () => {
  50. this.destory().catch((e) => console.log(e))
  51. })
  52. process.once('SIGTERM', () => {
  53. this.destory().catch((e) => console.log(e))
  54. })
  55. }
  56. public async start(): Promise<void> {
  57. this.listen()
  58. // await this.bot.start()
  59. }
  60. private listen(): void {
  61. this.server = this.app.listen(this.option.port, () => {
  62. console.log(`App listening on the port ${this.option.port}`)
  63. })
  64. }
  65. public async destory(): Promise<void> {
  66. if (this.server) {
  67. this.server.close()
  68. }
  69. if (this.db) {
  70. await this.db.close()
  71. }
  72. process.exit(0)
  73. }
  74. async init(): Promise<void> {
  75. this.initializeConfig()
  76. this.initializeMiddlewares()
  77. this.initializeControllers()
  78. this.initializeErrorHandling()
  79. await this.initializeDatabase()
  80. await this.initializeConstants()
  81. // await defaultSolanaHelper.getProvider()
  82. }
  83. private initializeConfig(): void {
  84. // 设置密钥
  85. this.app.set('jwtTokenSecret', process.env.JWT_SECRET ?? '666')
  86. // view engine setup
  87. this.app.set('views', path.join(__dirname, 'views'))
  88. this.app.set('view engine', 'ejs')
  89. }
  90. private initializeMiddlewares(): void {
  91. this.app.use(
  92. helmet({
  93. contentSecurityPolicy: false,
  94. })
  95. )
  96. this.app.use(logger('dev'))
  97. this.app.use(cookieParser(process.env.COOKIE_SECRET))
  98. this.app.use(express.json({ verify: deleteRequestBodySaver }))
  99. this.app.use(express.urlencoded({ extended: true }))
  100. this.app.use(
  101. express.static(path.join(__dirname, '../public'), {
  102. setHeaders(res) {
  103. res.set('Access-Control-Allow-Origin', '*')
  104. },
  105. })
  106. )
  107. this.app.use(setHeaderMiddleware)
  108. }
  109. private initializeControllers(): void {
  110. const controllers = this.option.controllers
  111. controllers.forEach((controller) => {
  112. this.app.use(controller.path, controller.router)
  113. })
  114. }
  115. private initializeErrorHandling(): void {
  116. this.app.use((_req, res) => {
  117. res.status(404)
  118. res.send('This api does not exist!')
  119. })
  120. this.app.use(errorMiddleware)
  121. }
  122. private async initializeDatabase(force = false): Promise<void> {
  123. this.db = await sequelize.sync({ force })
  124. }
  125. private async initializeConstants(): Promise<void> {
  126. // const SolFeeReceiver = await Constant.get('SolFeeReceiver')
  127. // if (!SolFeeReceiver) {
  128. // throw new Error('SolFeeReceiver not set')
  129. // }
  130. // const SolFeeBps = await Constant.get('SolFeeBps')
  131. // if (!SolFeeBps) {
  132. // throw new Error('SolFeeBps not set')
  133. // }
  134. // const bootEndpoints = await Constant.get('BootEndpoints')
  135. // if (!bootEndpoints) {
  136. // throw new Error('BootEndpoints not set')
  137. // }
  138. }
  139. }