aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/tests/shared/mock-servers/shared.ts
blob: 2356424392f3fdf729456bb20cb55aa610673587 (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 { AddressInfo } from 'net'

function randomListen (app: Express) {
  return new Promise<Server>(res => {
    const server = app.listen(0, () => res(server))
  })
}

function getPort (server: Server) {
  const address = server.address() as AddressInfo

  return address.port
}

function terminateServer (server: Server) {
  if (!server) return Promise.resolve()

  return new Promise<void>((res, rej) => {
    server.close(err => {
      if (err) return rej(err)

      return res()
    })
  })
}

export {
  randomListen,
  getPort,
  terminateServer
}