-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.js
66 lines (56 loc) · 1.53 KB
/
routes.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
import { Router } from "https://deno.land/x/oak/mod.ts";
import RouteSet from "./routes/route-set.js";
import MissingRouteError from "./errors/missing-route.js";
/**
* Routes are used to collect all routes defined in `RouteSet`s and
* connect them to the `Oak.Router` that actually does the work of
* routing requests to their handlers.
*/
export default class Routes {
constructor(app) {
this.app = app;
this.router = new Router();
this.set = new RouteSet(this.router, this.app);
this.draw = this.set.draw.bind(this.set);
}
/*
* Create the AllowedMethods middleware to insert a header based on
* the given routes.
*/
get methods() {
return this.router.allowedMethods();
}
/**
* Compile all routes into Oak middleware.
*/
get all() {
return this.router.routes();
}
/**
* Find the first matching route given the controller, action, and
* parameters.
*/
resolve(controller, action, params = {}, host = null) {
if (typeof controller === "string") {
return controller;
}
const keys = Object.keys(params);
const route = this.set.routes.find(
(route) => route.controller === controller && route.action === action,
);
if (!route) {
throw new MissingRouteError(controller, action, params);
}
const path = keys.reduce(
(k, p) => p.replace(`:${k}`, params[k]),
route.path,
);
if (host) {
return `${host}/${path}`;
}
return path;
}
forEach(iterator) {
return this.set.routes.forEach(iterator);
}
}