aboutsummaryrefslogtreecommitdiff
path: root/e2e/lib/TestServer.ts
blob: c010e37a820eca14f4c42b90bb4df388a5561d52 (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import * as http from 'http';
import * as net from 'net'
import express from 'express';

type HandlerFunc = (req: express.Request, res: express.Response) => void;

export default class TestServer {
  private http?: http.Server;

  private app: express.Application;

  constructor(
    private port = 0,
    private address = '127.0.0.1',
  ){
    this.app = express();
  }

  handle(path: string, f: HandlerFunc): TestServer {
    this.app.get(path, f);
    return this;
  }

  receiveContent(path: string, content: string): TestServer {
    this.app.get(path, (_req: express.Request, res: express.Response) => {
      res.status(200).send(content)
    });
    return this;
  }
  
  url(path: string = '/'): string {
    if (!this.http) {
      throw new Error('http server not started');
    }

    let addr = this.http.address() as net.AddressInfo;
    return `http://${addr.address}:${addr.port}${path}`
  }

  start(): Promise<void>  {
    if (this.http) {
      throw new Error('http server already started');
    }

    this.http = http.createServer(this.app)
    return new Promise((resolve) => {
      this.http!!.listen(this.port, this.address, () => {
        resolve();
      })
    });
  }

  stop(): Promise<void> {
    if (!this.http) {
      return Promise.resolve();
    }
    return new Promise((resolve) => {
      this.http!!.close(() => {
        this.http = undefined;
        resolve();
      });
    })
  }
}