-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathresponse-base.js
119 lines (101 loc) · 2.56 KB
/
response-base.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
/**
* Module dependencies.
*/
const utils = require('./utils');
/**
* Expose `ResponseBase`.
*/
module.exports = ResponseBase;
/**
* Initialize a new `ResponseBase`.
*
* @api public
*/
function ResponseBase() {}
/**
* Get case-insensitive `field` value.
*
* @param {String} field
* @return {String}
* @api public
*/
ResponseBase.prototype.get = function (field) {
return this.header[field.toLowerCase()];
};
/**
* Set header related properties:
*
* - `.type` the content type without params
*
* A response of "Content-Type: text/plain; charset=utf-8"
* will provide you with a `.type` of "text/plain".
*
* @param {Object} header
* @api private
*/
ResponseBase.prototype._setHeaderProperties = function (header) {
// TODO: moar!
// TODO: make this a util
// content-type
const ct = header['content-type'] || '';
this.type = utils.type(ct);
// params
const parameters = utils.params(ct);
for (const key in parameters) {
if (Object.prototype.hasOwnProperty.call(parameters, key))
this[key] = parameters[key];
}
this.links = {};
// links
try {
if (header.link) {
this.links = utils.parseLinks(header.link);
}
} catch (err) {
// ignore
}
};
/**
* Set flags such as `.ok` based on `status`.
*
* For example a 2xx response will give you a `.ok` of __true__
* whereas 5xx will be __false__ and `.error` will be __true__. The
* `.clientError` and `.serverError` are also available to be more
* specific, and `.statusType` is the class of error ranging from 1..5
* sometimes useful for mapping respond colors etc.
*
* "sugar" properties are also defined for common cases. Currently providing:
*
* - .noContent
* - .badRequest
* - .unauthorized
* - .notAcceptable
* - .notFound
*
* @param {Number} status
* @api private
*/
ResponseBase.prototype._setStatusProperties = function (status) {
const type = Math.trunc(status / 100);
// status / class
this.statusCode = status;
this.status = this.statusCode;
this.statusType = type;
// basics
this.info = type === 1;
this.ok = type === 2;
this.redirect = type === 3;
this.clientError = type === 4;
this.serverError = type === 5;
this.error = type === 4 || type === 5 ? this.toError() : false;
// sugar
this.created = status === 201;
this.accepted = status === 202;
this.noContent = status === 204;
this.badRequest = status === 400;
this.unauthorized = status === 401;
this.notAcceptable = status === 406;
this.forbidden = status === 403;
this.notFound = status === 404;
this.unprocessableEntity = status === 422;
};