aboutsummaryrefslogtreecommitdiffhomepage
path: root/packages/tests/src/shared/mock-servers/mock-429.ts
blob: 5fcb1447dc9afefc6f21e2d3db654a61a1b2e4b3 (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
import express from 'express'
import { Server } from 'http'
import { getPort, randomListen, terminateServer } from './shared.js'

export class Mock429 {
  private server: Server
  private responseSent = false

  async initialize () {
    const app = express()

    app.get('/', (req: express.Request, res: express.Response, next: express.NextFunction) => {

      if (!this.responseSent) {
        this.responseSent = true

        // Retry after 5 seconds
        res.header('retry-after', '2')
        return res.sendStatus(429)
      }

      return res.sendStatus(200)
    })

    this.server = await randomListen(app)

    return getPort(this.server)
  }

  terminate () {
    return terminateServer(this.server)
  }
}