-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequest-schema.ts
79 lines (70 loc) · 1.94 KB
/
request-schema.ts
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
/**
* Schema to match the request.
*/
// serializable
export type MockRequestSchema = {
/**
* The pattern to match the request URL.
*/
url: string;
/**
* Pattern type:
* - 'urlpattern': match request URL by URLPattern (default).
* - 'regexp': match request URL by regular expression.
*/
patternType?: 'urlpattern' | 'regexp';
/**
* The request method for matching.
*/
method?: HttpMethod;
/**
* The query parameters for matching, defined as key-value pairs.
*/
query?: Record<string, string | number | null>;
/**
* The request headers for matching, defined as key-value pairs.
*/
headers?: Record<string, string | null>;
/**
* The request body for matching, defined as a string or JSON.
*/
body?: string | Record<string, unknown> | Array<unknown>;
/**
* Flag to output debug info on server.
*/
debug?: boolean;
};
export type MockRequestSchemaInit =
| string
| RegExp
| {
url: string | RegExp;
patternType?: MockRequestSchema['patternType'];
method?: MockRequestSchema['method'];
query?: MockRequestSchema['query'];
headers?: MockRequestSchema['headers'];
body?: MockRequestSchema['body'];
debug?: MockRequestSchema['debug'];
};
export function buildMockRequestSchema(init: MockRequestSchemaInit): MockRequestSchema {
const initObj = toMockRequestSchemaObject(init);
const { url, ...rest } = initObj;
if (url instanceof RegExp) rest.patternType = 'regexp';
// always convert url to string to handle regexp
const urlStr = url.toString();
return Object.assign({ url: urlStr }, rest);
}
export function toMockRequestSchemaObject(init: MockRequestSchemaInit) {
if (!init) throw new Error('Request schema cannot be empty.');
return typeof init === 'string' || init instanceof RegExp ? { url: init } : init;
}
type HttpMethod =
| 'GET'
| 'HEAD'
| 'POST'
| 'PUT'
| 'DELETE'
| 'CONNECT'
| 'OPTIONS'
| 'TRACE'
| 'PATCH';