-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmsw-config.ts
More file actions
508 lines (434 loc) · 13.8 KB
/
msw-config.ts
File metadata and controls
508 lines (434 loc) · 13.8 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
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
import {
rest,
RestHandler,
setupWorker,
type RestRequest,
type SetupWorkerApi,
MockedRequest,
} from 'msw';
import { StartReturnType } from 'msw/lib/types/setupWorker/glossary';
import PassthroughRegistry from './passthrough-registry';
import type { Server } from 'miragejs';
import type { HTTPVerb, RouteHandler, ServerConfig } from 'miragejs/server';
import type { AnyFactories, AnyModels, AnyRegistry } from 'miragejs/-types';
type RawHandler = RouteHandler<AnyRegistry> | {};
type ResponseCode = number;
/** code, headers, serialized response */
type ResponseData = [ResponseCode, { [k: string]: string }, string | undefined];
/** e.g. "/movies/:id" */
type Shorthand = string;
type RouteArgs =
| [RouteOptions]
| [Record<string, unknown>, ResponseCode]
| [Function, ResponseCode]
| [Shorthand, RouteOptions]
| [Shorthand, ResponseCode, RouteOptions];
type RouteArguments = [
RawHandler | undefined,
ResponseCode | undefined,
RouteOptions,
];
type BaseHandler = (path: string, ...args: RouteArgs) => void;
type MirageServer = {
registerRouteHandler: (
verb: HTTPVerb,
path: string,
rawHandler?: RawHandler,
customizedCode?: ResponseCode,
options?: unknown
) => (request: RestRequest) => ResponseData | PromiseLike<ResponseData>;
shouldLog: () => boolean;
get?: BaseHandler;
post?: BaseHandler;
put?: BaseHandler;
delete?: BaseHandler;
del?: BaseHandler;
patch?: BaseHandler;
head?: BaseHandler;
options?: BaseHandler;
};
type RouteOptions = {
/** JSON-api option */
coalesce?: boolean;
/**
* Pretender treats a boolean timing option as "async", number as ms delay.
* TODO: Not sure what MSW does yet.
*/
timing?: boolean | number;
};
type SetupWorkerApiWithStartPromise = SetupWorkerApi & {
_startPromise: StartReturnType;
};
const defaultRouteOptions = {
coalesce: false,
timing: undefined,
} satisfies RouteOptions;
/**
* Determine if the object contains a valid option.
*
* @method isOption
* @param {Object} option An object with one option value pair.
* @return {Boolean} True if option is a valid option, false otherwise.
* @private
*/
function isOption(option: unknown): option is RouteOptions {
if (!option || typeof option !== 'object') {
return false;
}
let allOptions = Object.keys(defaultRouteOptions);
let optionKeys = Object.keys(option);
for (let i = 0; i < optionKeys.length; i++) {
let key = optionKeys[i];
if (allOptions.indexOf(key) > -1) {
return true;
}
}
return false;
}
/**
* Extract arguments for a route.
*
* @method extractRouteArguments
* @param {Array} args Of the form [options], [object, code], [function, code]
* [shorthand, options], [shorthand, code, options]
* @return {Array} [handler (i.e. the function, object or shorthand), code,
* options].
*/
function extractRouteArguments(args: RouteArgs): RouteArguments {
let result: RouteArguments = [undefined, undefined, {}];
for (const arg of args) {
if (isOption(arg)) {
result[2] = { ...defaultRouteOptions, ...arg };
} else if (typeof arg === 'number') {
result[1] = arg;
} else {
result[0] = arg;
}
}
return result;
}
export default class MswConfig {
urlPrefix?: string;
namespace?: string;
timing?: number;
msw?: SetupWorkerApiWithStartPromise;
mirageServer?: MirageServer;
// TODO: infer models and factories
mirageConfig?: ServerConfig<AnyModels, AnyFactories>;
handlers: RestHandler[] = [];
private passthroughs;
private passthroughChecks: ((req: MockedRequest) => boolean)[] = [];
get?: BaseHandler;
post?: BaseHandler;
put?: BaseHandler;
delete?: BaseHandler;
del?: BaseHandler;
patch?: BaseHandler;
head?: BaseHandler;
options?: BaseHandler;
constructor() {
this.passthroughs = new PassthroughRegistry();
}
create(
server: MirageServer,
mirageConfig: ServerConfig<AnyModels, AnyFactories>
) {
this.mirageServer = server;
this.mirageConfig = mirageConfig;
this.config(mirageConfig);
const verbs = [
['get'] as const,
['post'] as const,
['put'] as const,
['delete', 'del'] as const,
['patch'] as const,
['head'] as const,
['options'] as const,
];
verbs.forEach(([verb, alias]) => {
this[verb] = (path: string, ...args: RouteArgs) => {
let [rawHandler, customizedCode, options] = extractRouteArguments(args);
// This assertion is for TypeScript, we don't expect it to happen
if (!this.mirageServer) {
throw new Error('Lost the mirageServer');
}
let handler = this.mirageServer.registerRouteHandler(
verb,
path,
rawHandler,
customizedCode,
options
);
let fullPath = this._getFullPath(path);
let mswHandler = rest[verb](fullPath, async (req, res, ctx) => {
let queryParams: Record<string, string | string[]> = {};
req.url.searchParams.forEach((value, key) => {
let newValue: string | string[] = value;
if (key.includes('[]')) {
key = key.replace('[]', '');
newValue = [...(queryParams[key] || []), value];
}
queryParams[key] = newValue;
});
let request = Object.assign(req, {
requestBody:
typeof req.body === 'string'
? req.body
: JSON.stringify(req.body),
queryParams: queryParams,
});
let [code, headers, response] = await handler(request);
if (code === 204) {
// MirageJS Incorrectly sets the body to "" on a 204.
response = undefined;
}
return res(ctx.status(code), ctx.delay(this.timing), (res) => {
res.body = response;
Object.entries(headers || {}).forEach(([key, value]) => {
res.headers.set(key, value);
});
return res;
});
});
if (this.msw) {
this.msw.use(mswHandler);
} else {
this.handlers.push(mswHandler);
}
};
server[verb] = this[verb];
if (alias) {
this[alias] = this[verb];
server[alias] = this[verb];
}
});
}
// TODO: infer models and factories
config(mirageConfig: ServerConfig<AnyModels, AnyFactories>) {
/**
Sets a string to prefix all route handler URLs with.
Useful if your app makes API requests to a different port.
```js
createServer({
routes() {
this.urlPrefix = 'http://localhost:8080'
}
})
```
*/
this.urlPrefix = this.urlPrefix || mirageConfig.urlPrefix || '';
/**
Set the base namespace used for all routes defined with `get`, `post`, `put` or `del`.
For example,
```js
createServer({
routes() {
this.namespace = '/api';
// this route will handle the URL '/api/contacts'
this.get('/contacts', 'contacts');
}
})
```
Note that only routes defined after `this.namespace` are affected. This is useful if you have a few one-off routes that you don't want under your namespace:
```js
createServer({
routes() {
// this route handles /auth
this.get('/auth', function() { ...});
this.namespace = '/api';
// this route will handle the URL '/api/contacts'
this.get('/contacts', 'contacts');
};
})
```
If your app is loaded from the filesystem vs. a server (e.g. via Cordova or Electron vs. `localhost` or `https://yourhost.com/`), you will need to explicitly define a namespace. Likely values are `/` (if requests are made with relative paths) or `https://yourhost.com/api/...` (if requests are made to a defined server).
For a sample implementation leveraging a configured API host & namespace, check out [this issue comment](https://github.com/miragejs/ember-cli-mirage/issues/497#issuecomment-183458721).
@property namespace
@type String
@public
*/
this.namespace = this.namespace || mirageConfig.namespace || '';
}
/**
* Builds a full path for Pretender to monitor based on the `path` and
* configured options (`urlPrefix` and `namespace`).
*
* @private
* @hide
*/
_getFullPath(path: string) {
path = path[0] === '/' ? path.slice(1) : path;
let fullPath = '';
let urlPrefix = this.urlPrefix ? this.urlPrefix.trim() : '';
let namespace = '';
// if there is a urlPrefix and a namespace
if (this.urlPrefix && this.namespace) {
if (
this.namespace[0] === '/' &&
this.namespace[this.namespace.length - 1] === '/'
) {
namespace = this.namespace
.substring(0, this.namespace.length - 1)
.substring(1);
}
if (
this.namespace[0] === '/' &&
this.namespace[this.namespace.length - 1] !== '/'
) {
namespace = this.namespace.substring(1);
}
if (
this.namespace[0] !== '/' &&
this.namespace[this.namespace.length - 1] === '/'
) {
namespace = this.namespace.substring(0, this.namespace.length - 1);
}
if (
this.namespace[0] !== '/' &&
this.namespace[this.namespace.length - 1] !== '/'
) {
namespace = this.namespace;
}
}
// if there is a namespace and no urlPrefix
if (this.namespace && !this.urlPrefix) {
if (
this.namespace[0] === '/' &&
this.namespace[this.namespace.length - 1] === '/'
) {
namespace = this.namespace.substring(0, this.namespace.length - 1);
}
if (
this.namespace[0] === '/' &&
this.namespace[this.namespace.length - 1] !== '/'
) {
namespace = this.namespace;
}
if (
this.namespace[0] !== '/' &&
this.namespace[this.namespace.length - 1] === '/'
) {
let namespaceSub = this.namespace.substring(
0,
this.namespace.length - 1
);
namespace = `/${namespaceSub}`;
}
if (
this.namespace[0] !== '/' &&
this.namespace[this.namespace.length - 1] !== '/'
) {
namespace = `/${this.namespace}`;
}
}
// if no namespace
if (!this.namespace) {
namespace = '';
}
// check to see if path is a FQDN. if so, ignore any urlPrefix/namespace that was set
if (/^https?:\/\//.test(path)) {
fullPath += path;
} else {
// otherwise, if there is a urlPrefix, use that as the beginning of the path
if (urlPrefix.length) {
fullPath +=
urlPrefix[urlPrefix.length - 1] === '/' ? urlPrefix : `${urlPrefix}/`;
}
// add the namespace to the path
fullPath += namespace;
// add a trailing slash to the path if it doesn't already contain one
if (fullPath[fullPath.length - 1] !== '/') {
fullPath += '/';
}
// finally add the configured path
fullPath += path;
// if we're making a same-origin request, ensure a / is prepended and
// dedup any double slashes
if (!/^https?:\/\//.test(fullPath)) {
fullPath = `/${fullPath}`;
fullPath = fullPath.replace(/\/+/g, '/');
}
}
return fullPath;
}
passthrough(...args: (string | HTTPVerb[])[]) {
let verbs: HTTPVerb[] = [
'get',
'post',
'put',
'delete',
'patch',
'options',
'head',
];
let lastArg = args[args.length - 1];
let paths: string[] = [];
if (args.length === 0) {
paths = ['/**', '/'];
} else if (Array.isArray(lastArg)) {
verbs = lastArg;
}
// Need to loop because TS doesn't know if they're strings or arrays
for (const arg of args) {
if (typeof arg === 'string') {
paths.push(arg);
}
}
paths.forEach((path) => {
if (typeof path === 'function') {
this.passthroughChecks.push(path);
} else {
let fullPath = this._getFullPath(path);
this.passthroughs.add(fullPath, verbs);
}
});
}
start() {
this.msw = setupWorker(...this.handlers) as SetupWorkerApiWithStartPromise;
let logging = this.mirageConfig?.logging || false;
this.msw._startPromise = this.msw.start({
quiet: !logging,
onUnhandledRequest: (req) => {
const verb = req.method.toUpperCase();
const path = req.url.pathname;
// Check passthrough functions
let shouldPassthrough = this.passthroughChecks.some(
(passthroughCheck) => passthroughCheck(req)
);
// Also check other passthroughs
const recognized = this.passthroughs
.retrieve(req.url.host)
?.get(verb)
?.recognize(path);
const match = recognized?.[0];
if (shouldPassthrough || match) {
if (this.mirageServer?.shouldLog()) {
console.log(
`Mirage: Passthrough request for ${verb} ${req.url.href}`
);
}
// @ts-expect-error this seems to be an issue in msw types
req.passthrough();
}
// Log a warning for any requests for resources that aren't static assets of the page itself
else if (
req.url.host !== window.location.host &&
this.mirageServer?.shouldLog()
) {
let namespaceError = '';
if (this.namespace === '') {
namespaceError = 'There is no existing namespace defined.';
} else {
namespaceError = `The existing namespace is ${this.namespace}`;
}
console.warn(
`Mirage: Your app tried to ${verb} '${req.url.href}', but there was no route defined to handle this request. Add a passthrough or define a route for this endpoint in your routes() config.\nDid you forget to define a namespace? ${namespaceError}`
);
}
},
});
}
shutdown() {
this.msw?.stop();
}
}