-
Notifications
You must be signed in to change notification settings - Fork 4
/
Route.js
252 lines (227 loc) · 5.92 KB
/
Route.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
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
"use strict";
var _ = require('lodash')
, AccessError = require('dodo/errors').AccessError
, NotFoundError = require('dodo/errors').NotFoundError
, Promise = require('bluebird');
// Token used to indicate that no result was returned from a handler.
var NO_RESULT = {};
/**
* @constructor
*/
function Route(opt) {
/**
* @type {express.Router}
*/
this.expressRouter = opt.expressRouter;
/**
* @type {String}
*/
this.method = opt.method;
/**
* @type {String|RegExp}
*/
this.path = opt.path;
/**
* @type {function(req, transaction):boolean}
*/
this.defaultAuthHandler = opt.defaultAuthHandler;
/**
* @type {Number}
*/
this.unauthenticatedStatusCode = opt.unauthenticatedStatusCode;
/**
* @type {Array.<function (Request, Response, Transaction)>}
*/
this.authHandlers = [];
/**
* @type {Array.<function (Request, Response, function)>}
*/
this.expressMiddleware = [];
/**
* @type {function (Request, Response, next)}
*/
this.handlerFunc = null;
}
/**
* Installs an express middleware to the route.
*
* @param {function(IncomingMessage, function)} middleware
* @returns {Route}
*/
Route.prototype.middleware = function (middleware) {
if (this.handlerFunc) {
throw new Error('You must call middleware(func) before handler(func)');
}
this.expressMiddleware.push(middleware);
return this;
};
/**
* Installs an authentication handler for the route.
*
* @see Router#get for examples.
* @param {function(IncomingMessage)=} authHandler
* @returns {Route}
*/
Route.prototype.auth = function (authHandler) {
if (this.handlerFunc) {
throw new Error('You must call auth(func) before handler(func)');
}
if (authHandler) {
this.authHandlers.push(authHandler);
}
return this;
};
/**
* Makes the route public by removing all authentications (including the defaultAuth method).
*
* @returns {Route}
*/
Route.prototype.public = function () {
this.authHandlers = [];
this.defaultAuthHandler = null;
this._public = true;
return this;
};
/**
* This handler sends response by itself and we shouldn't apply default response sending actions for this one.
*
* Handler must return promise, which doesn't resolve until res.send is called.
*
* @returns {Route}
*/
Route.prototype.customResponse = function () {
this._omitResultHandlers = true;
return this;
};
/**
* Installs a handler for the route.
*
* @see Router#get for examples.
* @param {function(IncomingMessage, ServerResponse, Next)} handler
* @returns {Route}
*/
Route.prototype.handler = function (handler) {
if (this.handlerFunc) {
throw new Error('handler(func) can be called just once per Route instance');
}
this.handlerFunc = handler;
this.execute_();
return this;
};
/**
* @private
*/
Route.prototype.execute_ = function () {
var self = this;
this.expressRouter[this.method](this.path, function (req, res, next) {
// return for testing purposes...
return self.handlerMiddleware_(req, res, next);
});
};
/**
* @private
*/
Route.prototype.handlerMiddleware_ = function (req, res, next) {
var self = this;
var promise = Promise.resolve();
promise = promise.then(function () {
return self.handle_(req, res, next);
});
// return promise for testing purposes
return promise.then(function (result) {
if (result === NO_RESULT) {
if (!res.headersSent) {
throw new Error("When using .customResponse() handler, the promise returned must not resolve before the response has been sent. " +
"Requested path: " + req.path);
}
return;
}
if (!_.isObject(result) && !_.isString(result)) {
throw new NotFoundError();
} else {
sendResult(result, req, res);
}
if (!res.headersSent) {
throw new Error("Unexpected error, response was not sent by any handler for some reason. " +
"Requested path: " + req.path);
}
}).catch(next);
};
/**
* @private
*/
Route.prototype.handle_ = function (req, res, next) {
var self = this;
var context = {};
var authHandlers = (this.authHandlers && this.authHandlers.slice()) || [];
var promise = Promise.resolve();
_.forEach(self.expressMiddleware, function (middleware) {
promise = promise.then(function () {
return executeMiddleware(req, res, middleware);
});
});
if (!this._public) {
if (this.defaultAuthHandler) {
authHandlers.unshift(this.defaultAuthHandler);
} else {
throw new Error("No defaultAuthHandler set for non-public route. Requested path: " + req.path);
}
}
_.forEach(authHandlers, function (authHandler) {
promise = promise.then(function () {
return authHandler.call(context, req);
}).then(function (ret) {
if (_.isBoolean(ret)) {
if (!ret) {
throw new AccessError();
}
} else if (ret instanceof Error) {
throw ret;
} else {
throw new Error("Invalid return value from auth handler. Requested path: " + req.path);
}
});
});
return promise.then(function () {
var result = self.handlerFunc.call(context, req, res, next);
if (self._omitResultHandlers) {
return NO_RESULT;
} else {
return result;
}
});
};
module.exports = Route;
/**
* @private
*/
function executeMiddleware(req, res, middleware) {
return new Promise(function (resolve, reject) {
var next = function (err) {
if (err) {
reject(err);
} else {
resolve();
}
};
middleware(req, res, next);
});
}
/**
* @private
*/
function sendResult(result, req, res) {
if (Buffer.isBuffer(result)) {
res.send(result);
} else if (_.isObject(result)) {
res.set('Content-Type', 'application/json');
// Pretty print json in development and testing modes.
if (req.app.config.profile === 'development' || req.app.config.profile === 'testing') {
res.send(JSON.stringify(result, null, 2));
} else {
res.send(JSON.stringify(result));
}
} else {
res.send(result);
}
}