-
Notifications
You must be signed in to change notification settings - Fork 0
/
BuildableRoute.ts
204 lines (177 loc) · 7.34 KB
/
BuildableRoute.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import Negotiator = require("negotiator");
import {Route} from "./Route";
import {RouterEvent} from "../RouterEvent";
import {RouterResponse} from "../RouterResponse";
export class BuildableRoute implements Route, RouteBuilder {
private settings: {
handler?: (evt: RouterEvent) => Promise<RouterResponse>;
postProcessor?: (evt: RouterEvent, resp: RouterResponse, handlingRoutes: Route[]) => Promise<RouterResponse>;
pathRegex?: RegExp;
regexGroupToPathParamMap?: string[];
method?: string;
serializers?: { [mimeType: string]: (body: any) => Promise<string> | string };
} = {};
matches(evt: RouterEvent): boolean {
if (this.settings.method && this.settings.method !== evt.httpMethod) {
return false;
}
if (this.settings.pathRegex && !this.settings.pathRegex.test(evt.path)) {
return false;
}
if (this.settings.serializers) {
const negotiator = new Negotiator({headers: evt.headersLowerCase});
if (!negotiator.mediaType(Object.keys(this.settings.serializers))) {
return false;
}
}
return true;
}
async handle(evt: RouterEvent): Promise<RouterResponse> | null {
if (this.settings.handler) {
const calculatedPathParameters = {...evt.pathParameters};
// Map regex groups to pathParameters.
const pathRegexExec = this.settings.pathRegex.exec(evt.path);
for (let i = 1; i < pathRegexExec.length; i++) {
const pathValue = decodeURIComponent(pathRegexExec[i]);
if (this.settings.regexGroupToPathParamMap && this.settings.regexGroupToPathParamMap[i]) {
calculatedPathParameters[this.settings.regexGroupToPathParamMap[i]] = pathValue;
}
calculatedPathParameters[i.toString()] = pathValue;
}
const pathedRouterEvent = Object.assign(new RouterEvent(), evt);
pathedRouterEvent.pathParameters = calculatedPathParameters;
const resp = await this.settings.handler(pathedRouterEvent);
if (!resp) {
return resp;
}
if (this.settings.serializers) {
const negotiator = new Negotiator({headers: evt.headersLowerCase});
const mediaType = negotiator.mediaType(Object.keys(this.settings.serializers));
resp.body = await this.settings.serializers[mediaType](resp.body);
if (!resp.headers) {
resp.headers = {};
}
RouterResponse.setHeader(resp, "Content-Type", mediaType);
}
return resp;
}
return null;
}
postProcess(evt: RouterEvent, resp: RouterResponse, handlingRoutes: Route[]): Promise<RouterResponse> | null {
if (this.settings.postProcessor) {
return this.settings.postProcessor(evt, resp, handlingRoutes);
}
return null;
}
path(path: string | RegExp): this {
if (!path) {
throw new Error("path cannot be null");
}
if (this.settings.pathRegex) {
throw new Error("path is already defined");
}
if (typeof path === "string") {
// Turn path into a regex, replace {pathParam}s with regex groups
// and build the map that maps the group index to the path param name.
this.settings.regexGroupToPathParamMap = [""];
const sanitizedPathRegex = path
.replace(/[#-.]|[[-^]|[?|{}]/g, "\\$&")
.replace(/\\{[a-zA-Z][a-zA-Z0-9]*\\}/g, substr => {
const pathParamName = substr.replace(/^\\{/, "").replace(/\\}/, "");
this.settings.regexGroupToPathParamMap.push(pathParamName);
return "([0-9a-zA-Z._~!$&'()*+,;=:@%-]+)";
});
path = new RegExp(`^${sanitizedPathRegex}$`, "i");
}
if (path instanceof RegExp) {
this.settings.pathRegex = path;
} else {
throw new Error("unknown path type");
}
return this;
}
method(method: string): this {
if (!method) {
throw new Error("method cannot be null");
}
if (this.settings.method) {
throw new Error("method is already defined");
}
this.settings.method = method;
return this;
}
serializers(serializers: { [mimeType: string]: (body: any) => Promise<string> | string }): this {
if (!serializers) {
throw new Error("serializers cannot be null");
}
if (this.settings.serializers) {
throw new Error("serializers is already defined");
}
// For text mime-types without a charset specified add a default utf-8 version.
const serializersWithCharsets = {...serializers};
for (const type in serializers) {
if (typeof serializers[type] === "function" && /^(text\/[^;]+|application\/json)$/.test(type)) {
serializersWithCharsets[`${type}; charset=utf-8`] = serializers[type];
}
}
this.settings.serializers = serializersWithCharsets;
return this;
}
handler(handler: (evt: RouterEvent) => Promise<RouterResponse>): this {
if (!handler) {
throw new Error("handler cannot be null");
}
if (this.settings.handler) {
throw new Error("handler is already defined");
}
this.settings.handler = handler;
return this;
}
postProcessor(postProcessor: (evt: RouterEvent, resp: RouterResponse, handlingRoutes: Route[]) => Promise<RouterResponse>): this {
if (!postProcessor) {
throw new Error("postProcessor cannot be null");
}
if (this.settings.postProcessor) {
throw new Error("postProcessor is already defined");
}
this.settings.postProcessor = postProcessor;
return this;
}
}
export interface RouteBuilder {
/**
* Match requests with the given path.
*/
path(path: string | RegExp): this;
/**
* Match requests for the given method.
*/
method(method: string): this;
/**
* Match requests for clients than can accept one of the given mime-types
* and use the given serializer on the response body. The serializer will be
* called with the body if the handler returns a response. The serializer
* must return a string or Buffer, or Promise of such.
*
* eg:
* ```
* serializers({
* "application/json": cassava.serializers.jsonSerializer,
* "text/plain": body => body.toString()
* })
* ```
*
* @param serializers a map of mime-type to serializer function
*/
serializers(serializers: { [mimeType: string]: (body: any) => Promise<string | Buffer> | string | Buffer }): this;
/**
* Set the handler for this Route.
* @see routes.Route.handle
*/
handler(handler: (evt: RouterEvent) => Promise<RouterResponse | null | void> | RouterResponse | null | void): this;
/**
* Set the post processor for this Route.
* @see routes.Route.postProcess
*/
postProcessor(postProcessor: (evt: RouterEvent, resp: RouterResponse, handlingRoutes: Route[]) => Promise<RouterResponse | null | void> | RouterResponse | null | void): this;
}