-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (53 loc) · 1.4 KB
/
index.js
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
65
66
67
68
69
import { createServer } from 'node:http'
import { promisify } from 'node:util'
import express from 'express'
import fetch from 'node-fetch'
import { WebSocketServer } from 'ws'
class ExpressAsPromise {
constructor () {
this.app = express()
this.server = createServer(this.app)
this.wss = new WebSocketServer({ server: this.server })
}
async listen (port, host) {
await (new Promise((resolve, reject) => {
this.server.listen(port, host, err => {
if (err) {
return reject(err)
}
resolve()
})
}))
return this.url
}
async stop () {
if (!this.server.listening) {
return
}
await promisify(this.server.close.bind(this.server))()
}
async fetch (pathname, options) {
if (!this.server.listening) {
await this.listen()
}
const fullUrl = new URL(pathname, this.url)
return fetch(fullUrl.toString(), options)
}
get host () {
const address = this.server.address()
if (address.family === 'IPv4' && address.address !== '0.0.0.0') {
return address.address
}
if (address.family === 'IPv6' && address.address !== '::') {
return `[${address.address}]`
}
return 'localhost'
}
get port () {
return this.server.address().port
}
get url () {
return new URL(`http://${this.host}${this.port !== 80 ? `:${this.port}` : ''}/`)
}
}
export default ExpressAsPromise