-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.ts
60 lines (49 loc) · 1.25 KB
/
node.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
import http from 'http'
import {
EndpointMatcher,
ExactUrlPathnameMatcher,
} from '../matchers'
import {
BooleanMatcher,
} from '../matchers/BooleanMatcher'
import {
NodeHttpRouter,
} from '../node/NodeHttpRouter'
/*
Demo how to use router with native node native http server
run with:
pnpm run example-node-start
npm run example-node-start
yarn example-node-start
*/
const router = new NodeHttpRouter()
const [address, port] = ['localhost', 8080]
const server = http.createServer(router.serve).listen(port, address)
server.once('listening', () => {
// eslint-disable-next-line no-console
console.log(`started at http:https://${address}:${port}`)
})
router.addRoute({
// it's not necessary to type the matcher, but it give you a confidence
matcher: new EndpointMatcher<{ name: string }>('GET', /^\/hello\/(?<name>[^/]+)$/),
handler: ({ data: { res }, match }) => {
res.write(`Hello ${match.result.match.groups.name}!`)
res.end()
},
})
router.addRoute({
matcher: new ExactUrlPathnameMatcher(['/shutdown']),
handler: ({ data: { res } }) => {
res.write('Shutdown the server')
res.end()
server.close()
},
})
// 404 handler
router.addRoute({
matcher: new BooleanMatcher(true),
handler: ({ data: { res } }) => {
res.statusCode = 404
res.end()
},
})