UNPKG

1.77 kBJavaScriptView Raw
1'use strict'
2
3const send = require('@polka/send-type')
4const polka = require('polka')
5const cors = require('cors')
6const http = require('http')
7const { Buffer } = require('buffer')
8const getPort = require('./get-port')
9
10class 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
69module.exports = EchoServer