forked from capricorn86/happy-dom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FetchHandler.ts
54 lines (49 loc) · 1.7 KB
/
FetchHandler.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
import RelativeURL from '../location/RelativeURL';
import IRequestInit from './IRequestInit';
import IDocument from '../nodes/document/IDocument';
import IResponse from './IResponse';
import Response from './Response';
import NodeFetch from 'node-fetch';
/**
* Helper class for performing fetch.
*/
export default class FetchHandler {
/**
* Returns resource data asynchonously.
*
* @param document Document.
* @param url URL to resource.
* @param [init] Init.
* @returns Response.
*/
public static fetch(document: IDocument, url: string, init?: IRequestInit): Promise<IResponse> {
// We want to only load NodeFetch when it is needed to improve performance and not have direct dependencies to server side packages.
const taskManager = document.defaultView.happyDOM.asyncTaskManager;
return new Promise((resolve, reject) => {
const taskID = taskManager.startTask();
NodeFetch(RelativeURL.getAbsoluteURL(document.defaultView.location, url).href, init)
.then((response) => {
if (taskManager.getTaskCount() === 0) {
reject(new Error('Failed to complete fetch request. Task was canceled.'));
} else {
response.constructor['_ownerDocument'] = document;
for (const key of Object.keys(Response.prototype)) {
if (Response.prototype.hasOwnProperty(key) && key !== 'constructor') {
if (typeof Response.prototype[key] === 'function') {
response[key] = Response.prototype[key].bind(response);
} else {
response[key] = Response.prototype[key];
}
}
}
taskManager.endTask(taskID);
resolve(response);
}
})
.catch((error) => {
reject(error);
taskManager.cancelAll(error);
});
});
}
}