/
expres.js
415 lines (366 loc) · 9.74 KB
/
expres.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
var url = require('url')
, http = require('http')
, utils = require('./utils')
, expres = module.exports = {};
expres.middleware = function (req, res, next) {
if (!res.req) res.req = req;
if (!res.next) res.next = next;
Object.keys(expres.methods).forEach( function (method) {
// We don't override existing methods.
if (typeof res[method] === 'undefined') {
res[method] = expres.methods[method].bind(res);
}
});
if (next) next();
};
expres.methods = {
/**
* Set status `code`.
*
* @param {Number} code
* @return {ServerResponse}
*/
status: function(code){
this.statusCode = code;
return this;
},
/**
* Set Link header field with the given `links`.
*
* Examples:
*
* res.links({
* next: 'http://api.example.com/users?page=2',
* last: 'http://api.example.com/users?page=5'
* });
*
* @param {Object} links
* @return {ServerResponse}
*/
links: function(links){
return this.set('Link', Object.keys(links).map(function(rel){
return '<' + links[rel] + '>; rel="' + rel + '"';
}).join(', '));
},
/**
* Set the Content-Type to `type`.
*
* Example:
*
* res.type('application/json');
*
* @param {String} type
* @return {ServerResponse} for chaining
*/
type: function(type){
return this.set('Content-Type', type);
},
/**
* Send a response.
*
* Examples:
*
* res.send(new Buffer('wahoo'));
* res.send({ some: 'json' });
* res.send('<p>some html</p>');
* res.send(404, 'Sorry, cant find that');
* res.send(404);
*
* @param {Mixed} body or status
* @param {Mixed} body
* @return {ServerResponse}
*/
send: function(body){
var req = this.req
, head = 'HEAD' == req.method
, len;
// allow status / body
if (2 == arguments.length) {
// res.send(body, status) backwards compat
if ('number' != typeof body && 'number' == typeof arguments[1]) {
this.statusCode = arguments[1];
} else {
this.statusCode = body;
body = arguments[1];
}
}
switch (typeof body) {
// response status
case 'number':
this.get('Content-Type') || this.type('text/plain');
this.statusCode = body;
body = http.STATUS_CODES[body];
break;
// string defaulting to html
case 'string':
if (!this.get('Content-Type')) {
this.type('text/html; charset=utf-8');
}
break;
case 'boolean':
case 'object':
if (null === body) {
body = '';
} else if (Buffer.isBuffer(body)) {
this.get('Content-Type') || this.type('application/octet-stream');
} else {
return this.json(body);
}
break;
}
// populate Content-Length
if (undefined !== body && !this.get('Content-Length')) {
this.set('Content-Length', len = Buffer.isBuffer(body)
? body.length
: Buffer.byteLength(body));
}
// ETag support
// TODO: W/ support
// if (len > 1024) {
// if (!this.get('ETag')) {
// this.set('ETag', etag(body));
// }
// }
// freshness
// if (req.fresh) this.statusCode = 304;
// strip irrelevant headers
if (204 == this.statusCode || 304 == this.statusCode) {
this.removeHeader('Content-Type');
this.removeHeader('Content-Length');
body = '';
}
// respond
this.end(head ? null : body);
return this;
},
/**
* Send JSON response.
*
* Examples:
*
* res.json(null);
* res.json({ user: 'tj' });
* res.json(500, 'oh noes!');
* res.json(404, 'I dont have that');
*
* @param {Mixed} obj or status
* @param {Mixed} obj
* @return {ServerResponse}
*/
json: function(obj){
// allow status / body
if (2 == arguments.length) {
// res.json(body, status) backwards compat
if ('number' == typeof arguments[1]) {
this.statusCode = arguments[1];
} else {
this.statusCode = obj;
obj = arguments[1];
}
}
var body = JSON.stringify(obj, null, 2);
// content-type
this.get('Content-Type') || this.set('Content-Type', 'application/json; charset=utf-8');
return this.send(body);
},
/**
* Send JSON response with JSONP callback support.
*
* Examples:
*
* res.jsonp(null);
* res.jsonp({ user: 'tj' });
* res.jsonp(500, 'oh noes!');
* res.jsonp(404, 'I dont have that');
*
* @param {Mixed} obj or status
* @param {Mixed} obj
* @return {ServerResponse}
*/
jsonp: function(obj){
// allow status / body
if (2 == arguments.length) {
// res.json(body, status) backwards compat
if ('number' == typeof arguments[1]) {
this.statusCode = arguments[1];
} else {
this.statusCode = obj;
obj = arguments[1];
}
}
var body = JSON.stringify(obj, null, 2);
if (!this.req.query) {
this.req.query = url.parse(this.req.url, true).query;
}
var callback = this.req.query['callback'];
// content-type
this.set('Content-Type', 'application/json; charset=utf-8');
// jsonp
if (callback) {
this.set('Content-Type', 'text/javascript; charset=utf-8');
body = callback.replace(/[^\[\]\w$.]/g, '') + '(' + body + ');';
}
return this.send(body);
},
/**
* Respond to the Acceptable formats using an `obj`
* of content-type callbacks.
*
* Content-Type is set for you, however if you choose
* you may alter this within the callback using `res.type()`
* or `res.set('Content-Type', ...)`.
*
* res.format({
* 'text/plain': function(){
* res.send('hey');
* },
*
* 'text/html': function(){
* res.send('<p>hey</p>');
* },
*
* 'appliation/json': function(){
* res.send({ message: 'hey' });
* }
* });
*
* By default expres passes an `Error`
* with a `.status` of 406 to `next(err)`
* if a match is not made. If you provide
* a `.default` callback it will be invoked
* instead.
*
* @param {Object} obj
* @return {ServerResponse} for chaining
*/
format: function(obj){
var req = this.req
, next = req.next;
var fn = obj.default;
if (fn) delete obj.default;
var keys = Object.keys(obj);
var key = utils.accepts(keys, req.headers['Accept'] || req.headers['accept']);
this.set('Vary', 'Accept');
if (key) {
this.set('Content-Type', utils.normalizeType(key));
obj[key](req, this, next);
} else if (fn) {
fn();
} else {
var err = new Error('Not Acceptable');
err.status = 406;
err.types = utils.normalizeTypes(keys);
next(err);
}
return this;
},
/**
* Set header `field` to `val`, or pass
* an object of header fields.
*
* Examples:
*
* res.set('Accept', 'application/json');
* res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
*
* Aliased as `res.header()`.
*
* @param {String|Object} field
* @param {String} val
* @return {ServerResponse} for chaining
*/
set: function(field, val){
if (2 == arguments.length) {
this.setHeader(field, '' + val);
} else {
for (var key in field) {
this.setHeader(key, '' + field[key]);
}
}
return this;
},
/**
* Get value for header `field`.
*
* @param {String} field
* @return {String}
*/
get: function(field){
return this.getHeader(field);
},
/**
* Redirect to the given `url` with optional response `status`
* defaulting to 302.
*
* The given `url` can also be the name of a mapped url, for
* example by default expres supports "back" which redirects
* to the _Referrer_ or _Referer_ headers or "/".
*
* Examples:
*
* res.redirect('/foo/bar');
* res.redirect('http://example.com');
* res.redirect(301, 'http://example.com');
* res.redirect('http://example.com', 301);
* res.redirect('../login'); // /blog/post/1 -> /blog/login
*
* @param {String} toUrl
* @param {Number} code
*/
redirect: function(toUrl){
var req = this.req
, head = 'HEAD' == req.method
, status = 302
, body;
// allow status / toUrl
if (2 == arguments.length) {
if ('number' == typeof toUrl) {
status = toUrl;
toUrl = arguments[1];
} else {
status = arguments[1];
}
}
// setup redirect map
var map = { back: req.headers['Referrer'] || '/' };
// perform redirect
toUrl = map[toUrl] || toUrl;
// relative
if (!~toUrl.indexOf('://') && 0 != toUrl.indexOf('//')) {
// In express this fetches the app's mount point (root).
var path = '';
// relative to path
if ('.' == toUrl[0]) {
toUrl = url.parse(req.url).path + '/' + toUrl;
// relative to root
} else if ('/' != toUrl[0]) {
toUrl = '/' + toUrl;
}
// Absolute
var host = req.headers['host'] || req.headers['Host'];
toUrl = '//' + host + toUrl;
}
// Support text/{plain,html} by default
this.format({
'text/plain': function(){
body = http.STATUS_CODES[status] + '. Redirecting to ' + toUrl;
},
'text/html': function(){
var u = utils.escape(toUrl);
body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';
},
default: function(){
body = '';
}
});
// Respond
this.status(status);
this.set('Location', toUrl);
this.set('Content-Length', Buffer.byteLength(body));
this.end(head ? null : body);
}
};
// Alias for 'type'.
expres.methods.contentType = expres.methods.type;
// Alias for 'set'.
expres.methods.header = expres.methods.set;