Server.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { Configuration, Inject, InjectorService } from '@tsed/di';
  2. import { PlatformApplication } from '@tsed/common';
  3. import '@tsed/platform-express'; // /!\ keep this import
  4. import bodyParser from 'body-parser';
  5. import compress from 'compression';
  6. import cookieParser from 'cookie-parser';
  7. import methodOverride from 'method-override';
  8. import '@tsed/swagger';
  9. import { TypeORMService } from '@tsed/typeorm';
  10. import { ConnectionOptions } from 'typeorm';
  11. export const rootDir = __dirname;
  12. const connectionOptions: ConnectionOptions = {
  13. // The 'name' property must be set. Otherwise, the 'name' will be '0' and won't work well. -- 2021.04.05 Yuki Takei
  14. // see: https://github.com/TypedProject/tsed/blob/7630cda20a1f6fa3a692ecc3e6cd51d37bc3c45f/packages/typeorm/src/utils/createConnection.ts#L10
  15. name: 'default',
  16. type: process.env.TYPEORM_CONNECTION,
  17. host: process.env.TYPEORM_HOST,
  18. port: process.env.TYPEORM_PORT,
  19. database: process.env.TYPEORM_DATABASE,
  20. username: process.env.TYPEORM_USERNAME,
  21. password: process.env.TYPEORM_PASSWORD,
  22. synchronize: true,
  23. } as ConnectionOptions;
  24. @Configuration({
  25. rootDir,
  26. acceptMimes: ['application/json'],
  27. httpPort: process.env.PORT || 8080,
  28. httpsPort: false, // CHANGE
  29. mount: {
  30. '/': [
  31. `${rootDir}/controllers/*.ts`,
  32. `${rootDir}/middlewares/*.ts`,
  33. ],
  34. },
  35. componentsScan: [
  36. `${rootDir}/services/*.ts`,
  37. ],
  38. typeorm: [
  39. {
  40. ...connectionOptions,
  41. entities: [
  42. `${rootDir}/entities/*{.ts,.js}`,
  43. ],
  44. migrations: [
  45. `${rootDir}/migrations/*{.ts,.js}`,
  46. ],
  47. subscribers: [
  48. `${rootDir}/subscribers/*{.ts,.js}`,
  49. ],
  50. } as ConnectionOptions,
  51. ],
  52. swagger: [
  53. {
  54. path: '/docs',
  55. specVersion: '3.0.1',
  56. },
  57. ],
  58. exclude: [
  59. '**/*.spec.ts',
  60. ],
  61. })
  62. export class Server {
  63. @Inject()
  64. app: PlatformApplication;
  65. @Configuration()
  66. settings: Configuration;
  67. @Inject()
  68. injector: InjectorService;
  69. $beforeRoutesInit(): void {
  70. this.app
  71. .use(cookieParser())
  72. .use(compress({}))
  73. .use(methodOverride())
  74. .use(bodyParser.json())
  75. .use(bodyParser.urlencoded({
  76. extended: true,
  77. }));
  78. }
  79. async $onReady(): Promise<void> {
  80. // for synchromizing when boot
  81. this.injector.get<TypeORMService>(TypeORMService);
  82. }
  83. }