forked from capricorn86/happy-dom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
XMLHttpRequestUpload.ts
87 lines (80 loc) · 1.84 KB
/
XMLHttpRequestUpload.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
80
81
82
83
84
85
86
87
import { XMLHttpRequestEventTarget } from './XMLHttpRequestEventTarget';
import { ClientRequest } from 'http';
/**
*
*/
export default class XMLHttpRequestUpload extends XMLHttpRequestEventTarget {
private _contentType: string | null = null;
private _body = null;
/**
*
*/
constructor() {
super();
this.reset();
}
/**
*
*/
public reset(): void {
this._contentType = null;
this._body = null;
}
/**
*
* @param data
*/
public setData(data?: string | Buffer | ArrayBuffer | ArrayBufferView): void {
if (data == null) {
return;
}
if (typeof data === 'string') {
if (data.length !== 0) {
this._contentType = 'text/plain;charset=UTF-8';
}
this._body = Buffer.from(data, 'utf-8');
} else if (Buffer.isBuffer(data)) {
this._body = data;
} else if (data instanceof ArrayBuffer) {
const body = Buffer.alloc(data.byteLength);
const view = new Uint8Array(data);
for (let i = 0; i < data.byteLength; i++) {
body[i] = view[i];
}
this._body = body;
} else if (data.buffer && data.buffer instanceof ArrayBuffer) {
const body = Buffer.alloc(data.byteLength);
const offset = data.byteOffset;
const view = new Uint8Array(data.buffer);
for (let i = 0; i < data.byteLength; i++) {
body[i] = view[i + offset];
}
this._body = body;
} else {
throw new Error(`Unsupported send() data ${data}`);
}
}
/**
*
* @param headers
* @param loweredHeaders
*/
public finalizeHeaders(headers: object, loweredHeaders: object): void {
if (this._contentType && !loweredHeaders['content-type']) {
headers['Content-Type'] = this._contentType;
}
if (this._body) {
headers['Content-Length'] = this._body.length.toString();
}
}
/**
*
* @param request
*/
public startUpload(request: ClientRequest): void {
if (this._body) {
request.write(this._body);
}
request.end();
}
}