Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
146 lines (116 loc) · 3.44 KB
/
Copy pathindex.js
File metadata and controls
146 lines (116 loc) · 3.44 KB
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
/* global window, Response */
import Route from 'route-parser';
import isEqual from 'lodash/isEqual';
import statuses from 'statuses';
const mocks = {};
const origFetch = window.fetch;
function objectContainsObject(object, containerObject) {
return Object.keys(object).every(key => isEqual(object[key], containerObject[key]));
}
function getMockMatch(url, options = {}) {
const method = options.method ? options.method.toLowerCase() : 'get';
const mockUrl = Object.keys(mocks).find(urlKey =>
mocks[urlKey][method] && mocks[urlKey][method].route.match(url));
if (mockUrl) {
const mock = mocks[mockUrl][method];
// If there are options do a shallow check, otherwise use `optionEqualityCheck`.
if (mock.options) {
if (typeof mock.options === 'function' && !mock.options(options)) {
return false;
}
if (!objectContainsObject(mock.options, options)) {
return false;
}
}
return mock;
}
return false;
}
function handleResponse(rawResponse, isRejected) {
const body = rawResponse.body || rawResponse;
const bodyString = JSON.stringify(body);
const status = rawResponse.status || (isRejected ? 500 : 200);
const statusText = rawResponse.statusText || statuses[status];
const headers = rawResponse.headers || {
'Content-Type': 'application/json',
'Content-Length': bodyString.length,
};
const response = new Response(bodyString, {
status,
statusText,
headers,
});
return response;
}
function isJSONRequest(headers = {}) {
return Object.keys(headers).some(headerName =>
headerName.toLowerCase() === 'content-type' &&
headers[headerName] === 'application/json');
}
function fetchOverride(url, options = {}) {
try {
let formattedOptions = options;
// Parse body passed to response fn for convenience if it's a JSON request.
if (options.body && isJSONRequest(options.headers)) {
try {
formattedOptions = {
...options,
body: JSON.parse(options.body),
}
} catch (error) {
console.error('Could not parse JSON body', options);
}
}
const mock = getMockMatch(url, formattedOptions);
if (!mock) {
const method = formattedOptions.method || 'GET';
const error = new Error(`No mock found for ${method} ${url}`);
error.url = url;
error.options = formattedOptions;
throw error;
}
const result = mock.response(url, mock.route.match(url), formattedOptions);
if (!result) {
throw new Error('The fetch mock function must return a Promise or object/primitive');
}
if (typeof result === 'object' && result.then) {
return result.catch(r => handleResponse(r, true)).then(handleResponse);
}
return Promise.resolve(handleResponse(result));
} catch (error) {
return Promise.reject(error);
}
}
const createMock = method => (url, response, options) =>
(mocks[url] || (mocks[url] = {}))[method] = {
url,
response,
route: new Route(url),
options,
};
const mockster = {
delete: createMock('delete'),
get: createMock('get'),
patch: createMock('patch'),
post: createMock('post'),
put: createMock('put'),
};
function fetchUnmock(url, method) {
if (mocks[url]) {
delete mocks[url][method];
}
}
function fetchHook() {
window.fetch = fetchOverride;
}
function fetchUnhook() {
window.fetch = origFetch;
}
fetchHook();
export {
mockster as default,
mockster,
fetchUnmock,
fetchHook,
fetchUnhook,
};