]>
Commit | Line | Data |
---|---|---|
41fb13c3 | 1 | import express from 'express' |
cf0c8ee5 | 2 | import { Server } from 'http' |
f6500729 | 3 | import { randomInt } from '@shared/core-utils' |
cf0c8ee5 | 4 | import { terminateServer } from './utils' |
6f1b4fa4 C |
5 | |
6 | export class MockInstancesIndex { | |
cf0c8ee5 C |
7 | private server: Server |
8 | ||
a1587156 | 9 | private readonly indexInstances: { host: string, createdAt: string }[] = [] |
6f1b4fa4 C |
10 | |
11 | initialize () { | |
f6500729 | 12 | return new Promise<number>(res => { |
6f1b4fa4 C |
13 | const app = express() |
14 | ||
15 | app.use('/', (req: express.Request, res: express.Response, next: express.NextFunction) => { | |
16 | if (process.env.DEBUG) console.log('Receiving request on mocked server %s.', req.url) | |
17 | ||
18 | return next() | |
19 | }) | |
20 | ||
21 | app.get('/api/v1/instances/hosts', (req: express.Request, res: express.Response) => { | |
22 | const since = req.query.since | |
23 | ||
24 | const filtered = this.indexInstances.filter(i => { | |
25 | if (!since) return true | |
26 | ||
27 | return i.createdAt > since | |
28 | }) | |
29 | ||
30 | return res.json({ | |
31 | total: filtered.length, | |
32 | data: filtered | |
33 | }) | |
34 | }) | |
35 | ||
3c25d37a | 36 | const port = 42000 + randomInt(1, 1000) |
cf0c8ee5 | 37 | this.server = app.listen(port, () => res(port)) |
6f1b4fa4 C |
38 | }) |
39 | } | |
40 | ||
41 | addInstance (host: string) { | |
42 | this.indexInstances.push({ host, createdAt: new Date().toISOString() }) | |
43 | } | |
cf0c8ee5 C |
44 | |
45 | terminate () { | |
46 | return terminateServer(this.server) | |
47 | } | |
6f1b4fa4 | 48 | } |