about summary refs log tree commit diff
path: root/bskylink/src/index.ts
blob: c7d52681df317739da22963962692a360e360ca6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import events from 'node:events'
import type http from 'node:http'

import cors from 'cors'
import express from 'express'
import {createHttpTerminator, type HttpTerminator} from 'http-terminator'

import {type Config} from './config.js'
import {AppContext} from './context.js'
import i18n from './i18n.js'
import {default as routes, errorHandler} from './routes/index.js'

export * from './config.js'
export * from './db/index.js'
export * from './logger.js'

export class LinkService {
  public server?: http.Server
  private terminator?: HttpTerminator

  constructor(
    public app: express.Application,
    public ctx: AppContext,
  ) {}

  static async create(cfg: Config): Promise<LinkService> {
    let app = express()
    app.use(cors())
    app.use(i18n.init)

    const ctx = await AppContext.fromConfig(cfg)
    app = routes(ctx, app)
    app.use(errorHandler)

    return new LinkService(app, ctx)
  }

  async start() {
    this.server = this.app.listen(this.ctx.cfg.service.port)
    this.server.keepAliveTimeout = 90000
    this.terminator = createHttpTerminator({server: this.server})
    await events.once(this.server, 'listening')
  }

  async destroy() {
    this.ctx.abortController.abort()
    await this.terminator?.terminate()
    await this.ctx.db.close()
  }
}