-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
39 lines (30 loc) · 849 Bytes
/
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
const fp = require("fastify-plugin")
const pathToRegexp = require("path-to-regexp")
const routes = new Map()
function reverse(name, args, opts) {
const toPath = routes.get(name)
if (!toPath) {
throw new Error(`Route with name ${name} is not registered`)
}
return toPath(args, opts)
}
function plugin(fastify, _, next) {
fastify.decorate("reverse", reverse)
fastify.addHook("onRoute", (routeOptions) => {
if (routeOptions.name) {
if (routes.has(routeOptions.name)) {
throw new Error(
`Route with name ${routeOptions.name} already registered`,
)
}
routes.set(routeOptions.name, pathToRegexp.compile(routeOptions.url))
}
})
next()
}
module.exports = reverse
module.exports.routes = routes
module.exports.plugin = fp(plugin, {
fastify: ">= 1.6.0",
name: "reverse",
})