aboutsummaryrefslogtreecommitdiffhomepage
path: root/shared/extra-utils/mock-servers/mock-plugin-blocklist.ts
blob: d18f8224ff6382a9ce113e350ebf59b141a53eff (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
import * as express from 'express'
import { Server } from 'http'
import { randomInt } from '@shared/core-utils'

type BlocklistResponse = {
  data: {
    value: string
    action?: 'add' | 'remove'
    updatedAt?: string
  }[]
}

export class MockBlocklist {
  private body: BlocklistResponse
  private server: Server

  initialize () {
    return new Promise<number>(res => {
      const app = express()

      app.get('/blocklist', (req: express.Request, res: express.Response) => {
        return res.json(this.body)
      })

      const port = 42201 + randomInt(1, 100)
      this.server = app.listen(port, () => res(port))
    })
  }

  replace (body: BlocklistResponse) {
    this.body = body
  }

  terminate () {
    if (this.server) this.server.close()
  }
}