1 | 'use strict'
|
2 |
|
3 | const send = require('@polka/send-type')
|
4 | const polka = require('polka')
|
5 | const cors = require('cors')
|
6 | const http = require('http')
|
7 | const { Buffer } = require('buffer')
|
8 | const getPort = require('./get-port')
|
9 |
|
10 | class EchoServer {
|
11 | constructor (options = {}) {
|
12 | this.options = options
|
13 | this.port = options.port || 3000
|
14 | this.host = options.host || '127.0.0.1'
|
15 | this.started = false
|
16 | }
|
17 |
|
18 | async start () {
|
19 | if (!this.started) {
|
20 | if (this.options.findPort !== false) {
|
21 | this.port = await getPort(this.port)
|
22 | }
|
23 | this.server = http.createServer()
|
24 | this.polka = polka({ server: this.server })
|
25 | .use(cors())
|
26 | .use('/redirect', (req, res) => {
|
27 | send(res, 302, null, { Location: req.query.to })
|
28 | })
|
29 | .all('/echo/query', (req, res) => {
|
30 | send(res, 200, req.query)
|
31 | })
|
32 | .all('/echo/headers', (req, res) => {
|
33 | send(res, 200, req.headers)
|
34 | })
|
35 | .all('/echo', (req, res) => {
|
36 | send(res, 200, req)
|
37 | })
|
38 | .all('/download', (req, res) => {
|
39 | send(res, 200, Buffer.from(req.query.data || ''))
|
40 | })
|
41 |
|
42 | const listen = new Promise((resolve, reject) => {
|
43 | this.server.once('error', reject)
|
44 | this.polka.listen({ host: this.host, port: this.port }, () => {
|
45 | resolve()
|
46 | })
|
47 | })
|
48 | await listen
|
49 | this.started = true
|
50 | }
|
51 | return this
|
52 | }
|
53 |
|
54 | async stop () {
|
55 | if (this.started) {
|
56 | const stop = new Promise((resolve, reject) => {
|
57 | this.server.once('error', reject)
|
58 | this.server.close((err) => {
|
59 | err ? reject(err) : resolve()
|
60 | })
|
61 | })
|
62 | await stop
|
63 | this.started = false
|
64 | }
|
65 | return this
|
66 | }
|
67 | }
|
68 |
|
69 | module.exports = EchoServer
|