forked from wheresrhys/fetch-mock
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse-builder.js
197 lines (177 loc) · 5.48 KB
/
response-builder.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
const { getDebug } = require('./debug');
const responseConfigProps = [
'body',
'headers',
'throws',
'status',
'redirectUrl',
];
class ResponseBuilder {
constructor(options) {
this.debug = getDebug('ResponseBuilder()');
this.debug('Response builder created with options', options);
Object.assign(this, options);
}
exec() {
this.debug('building response');
this.normalizeResponseConfig();
this.constructFetchOpts();
this.constructResponseBody();
const realResponse = new this.fetchMock.config.Response(
this.body,
this.options
);
const proxyResponse = this.buildObservableResponse(realResponse);
return [realResponse, proxyResponse];
}
sendAsObject() {
if (responseConfigProps.some((prop) => this.responseConfig[prop])) {
if (
Object.keys(this.responseConfig).every((key) =>
responseConfigProps.includes(key)
)
) {
return false;
} else {
return true;
}
} else {
return true;
}
}
normalizeResponseConfig() {
// If the response config looks like a status, start to generate a simple response
if (typeof this.responseConfig === 'number') {
this.debug('building response using status', this.responseConfig);
this.responseConfig = {
status: this.responseConfig,
};
// If the response config is not an object, or is an object that doesn't use
// any reserved properties, assume it is meant to be the body of the response
} else if (typeof this.responseConfig === 'string' || this.sendAsObject()) {
this.debug('building text response from', this.responseConfig);
this.responseConfig = {
body: this.responseConfig,
};
}
}
validateStatus(status) {
if (!status) {
this.debug('No status provided. Defaulting to 200');
return 200;
}
if (
(typeof status === 'number' &&
parseInt(status, 10) !== status &&
status >= 200) ||
status < 600
) {
this.debug('Valid status provided', status);
return status;
}
throw new TypeError(`fetch-mock: Invalid status ${status} passed on response object.
To respond with a JSON object that has status as a property assign the object to body
e.g. {"body": {"status: "registered"}}`);
}
constructFetchOpts() {
this.options = this.responseConfig.options || {};
this.options.url = this.responseConfig.redirectUrl || this.url;
this.options.status = this.validateStatus(this.responseConfig.status);
this.options.statusText = this.fetchMock.statusTextMap[
String(this.options.status)
];
// Set up response headers. The empty object is to cope with
// new Headers(undefined) throwing in Chrome
// https://code.google.com/p/chromium/issues/detail?id=335871
this.options.headers = new this.fetchMock.config.Headers(
this.responseConfig.headers || {}
);
}
getOption(name) {
return this.fetchMock.getOption(name, this.route);
}
convertToJson() {
// convert to json if we need to
if (
this.getOption('sendAsJson') &&
this.responseConfig.body != null && //eslint-disable-line
typeof this.body === 'object'
) {
this.debug('Stringifying JSON response body');
this.body = JSON.stringify(this.body);
if (!this.options.headers.has('Content-Type')) {
this.options.headers.set('Content-Type', 'application/json');
}
}
}
setContentLength() {
// add a Content-Length header if we need to
if (
this.getOption('includeContentLength') &&
typeof this.body === 'string' &&
!this.options.headers.has('Content-Length')
) {
this.debug('Setting content-length header:', this.body.length.toString());
this.options.headers.set('Content-Length', this.body.length.toString());
}
}
constructResponseBody() {
// start to construct the body
this.body = this.responseConfig.body;
this.convertToJson();
this.setContentLength();
// On the server we need to manually construct the readable stream for the
// Response object (on the client this done automatically)
if (this.Stream) {
this.debug('Creating response stream');
const stream = new this.Stream.Readable();
if (this.body != null) { //eslint-disable-line
stream.push(this.body, 'utf-8');
}
stream.push(null);
this.body = stream;
}
this.body = this.body;
}
buildObservableResponse(response) {
const fetchMock = this.fetchMock;
response._fmResults = {};
// Using a proxy means we can set properties that may not be writable on
// the original Response. It also means we can track the resolution of
// promises returned by res.json(), res.text() etc
this.debug('Wrapping Response in ES proxy for observability');
return new Proxy(response, {
get: (originalResponse, name) => {
if (this.responseConfig.redirectUrl) {
if (name === 'url') {
this.debug(
'Retrieving redirect url',
this.responseConfig.redirectUrl
);
return this.responseConfig.redirectUrl;
}
if (name === 'redirected') {
this.debug('Retrieving redirected status', true);
return true;
}
}
if (typeof originalResponse[name] === 'function') {
this.debug('Wrapping body promises in ES proxies for observability');
return new Proxy(originalResponse[name], {
apply: (func, thisArg, args) => {
this.debug(`Calling res.${name}`);
const result = func.apply(response, args);
if (result.then) {
fetchMock._holdingPromises.push(result.catch(() => null));
originalResponse._fmResults[name] = result;
}
return result;
},
});
}
return originalResponse[name];
},
});
}
}
module.exports = (options) => new ResponseBuilder(options).exec();