This repository has been archived by the owner on Nov 27, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mod.ts
70 lines (57 loc) · 1.6 KB
/
mod.ts
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
70
import * as http from 'https://deno.land/[email protected]/http/server.ts'
import { EventEmitter } from 'https://deno.land/x/[email protected]/mod.ts'
import { getFreePort } from 'https://deno.land/x/[email protected]/mod.ts'
type Events = {
error: [Error]
listening: []
request: [http.ServerRequest]
close: []
}
export type ServerHandler = (req: http.ServerRequest) => void | Promise<void>
/**
* Ported from `net.AddressInfo`
*/
export type AddressInfo = {
family: string
address: string
port: number
}
export class Server extends EventEmitter<Events> {
#server?: http.Server
handler?: ServerHandler
constructor(handler?: ServerHandler) {
super()
this.handler = handler
}
async listen(addr?: string | http.HTTPOptions) {
if (!addr) addr = { port: await getFreePort(3000) }
try {
this.#server = http.serve(addr)
} catch (e) {
await this.emit('error', e)
throw e
}
this.emit('listening')
try {
for await (const req of this.#server!) {
await this.emit('request', req)
await this.handler?.(req)
}
} catch (e) {
await this.emit('error', e)
throw e
}
return this.#server
}
address(): string | AddressInfo {
const unixAddr = this.#server?.listener.addr as Deno.UnixAddr
const netAddr = this.#server?.listener.addr as Deno.NetAddr
if (unixAddr?.path) return unixAddr.path
else return { family: 'IPv4', address: netAddr.hostname, port: netAddr.port }
}
close() {
this.#server?.close()
this.emit('close')
}
}
export const createServer = (handler?: ServerHandler) => new Server(handler)