-
Notifications
You must be signed in to change notification settings - Fork 38
/
mock-intercept.request.ts
59 lines (51 loc) · 1.83 KB
/
mock-intercept.request.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
import { PluginRunner, RequestOptions, RequestPlugin } from '../core';
import { CUSTOM_MOCK_OPERATION_ID_HEADER, CUSTOM_MOCK_REQUEST_HEADER, MockInterceptFetchParameters, MockInterceptRequestParameters } from './mock-intercept.interface';
/**
* Plugin to intercept an API request for mock purposes
*/
export class MockInterceptRequest implements RequestPlugin {
protected options: MockInterceptRequestParameters;
/**
* Creates a new instance of the plugin
* @param options configuration options for the plugin
*/
constructor(options: Partial<MockInterceptRequestParameters> & MockInterceptFetchParameters) {
this.options = {
disabled: false,
filter: () => true,
...options
};
}
/** @inheritdoc */
public load(): PluginRunner<RequestOptions, RequestOptions> {
return {
transform: async (data: RequestOptions) => {
await this.options.adapter.initialize();
if (
this.options.disabled ||
(this.options.filter && !this.options.filter(data))
) {
return data;
}
const requestOption = {
...data,
method: data.method || 'GET'
};
delete requestOption.api;
const operationId = await this.options.adapter.retrieveOperationId(requestOption);
const mock = this.options.adapter.getMock(operationId);
const text = JSON.stringify(mock.mockData);
const blob = new Blob([text], { type: 'application/json' });
const basePath = URL.createObjectURL(blob);
const headers = data.headers || new Headers();
data.headers.append(CUSTOM_MOCK_OPERATION_ID_HEADER, operationId);
data.headers.append(CUSTOM_MOCK_REQUEST_HEADER, JSON.stringify(requestOption));
return {
method: 'GET',
basePath,
headers
};
}
};
}
}