-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmicro.ts
59 lines (48 loc) · 1.19 KB
/
micro.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
import http from 'http'
import {
send,
serve,
} from 'micro'
import {
EndpointMatcher,
ExactUrlPathnameMatcher,
} from '../matchers'
import {
BooleanMatcher,
} from '../matchers/BooleanMatcher'
import {
NodeHttpRouter,
} from '../node/NodeHttpRouter'
/*
Demo how to use router with micro@canary
run with:
pnpm run example-micro-start
npm run example-micro-start
yarn example-micro-start
*/
const router = new NodeHttpRouter()
const [address, port] = ['localhost', 8080]
const server = http.createServer(serve(router.serve)).listen(port, address)
server.once('listening', () => {
// eslint-disable-next-line no-console
console.log(`started at http://${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: ({ match }) => {
return `Hello ${match.result.match.groups.name}!`
},
})
router.addRoute({
matcher: new ExactUrlPathnameMatcher(['/shutdown']),
handler: () => {
server.close()
return 'Shutdown the server'
},
})
// 404 handler
router.addRoute({
matcher: new BooleanMatcher(true),
handler: ({ data: { res } }) => send(res, 404),
})