This repository has been archived by the owner on Jan 29, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathxhr.ts
431 lines (389 loc) · 11.5 KB
/
xhr.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
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
import { VTransmitFile } from "../classes/VTransmitFile";
import { VTransmitUploadContext } from "../classes/VTransmitUploadContext";
import { DriverInterface, UploadResult } from "../core/interfaces";
import {
VTransmitEvents,
UploadStatuses,
ErrType,
is_function,
} from "../core/utils";
import { Dictionary } from "../types";
export type ParamName = string | ((file: VTransmitFile) => string);
export type StaticOrDynamic<T> = T | ((files: VTransmitFile[]) => T);
function resolveStaticOrDynamic<T>(
x: StaticOrDynamic<T>,
files: VTransmitFile[]
): T {
if (is_function(x)) {
return x(files);
}
return x;
}
export enum ParamNameStyle {
Empty,
Indexed,
Brackets,
}
/**
* Responsibilities:
* - send and manage upload via transport
* - on progress: emit progress stats
* - on error: emit to vue-transmit & update file status
* - on timeout: emit to vue-transmit & update file status
* - on error: emit to vue-transmit & update file status
* - on success: emit to vue-transmit & update file status
* - once complete: emit to vue-transmit & update file status
*/
export type XHRDriverOptions<T = any> = {
/**
* A string representing the URL to send the request to
* or a function called with an array of files for the upload
* that returns a string url.
*/
url: StaticOrDynamic<string>;
/**
* The HTTP method to use, such as "GET", "POST", "PUT", "DELETE", etc.
* Ignored for non-HTTP(S) URLs.
*
* ```
* // default => "post"
* ```
*/
method?: StaticOrDynamic<string>;
/**
* The XMLHttpRequest.withCredentials property is a Boolean that indicates
* whether or not cross-site Access-Control requests should be made using
* credentials such as cookies, authorization headers or TLS client
* certificates. Setting withCredentials has no effect on same-site requests.
*/
withCredentials?: StaticOrDynamic<boolean>;
/**
* The XMLHttpRequest.timeout property is an unsigned long representing the
* number of milliseconds a request can take before automatically being
* terminated. The default value is 0, which means there is no timeout.
* Timeout shouldn't be used for synchronous XMLHttpRequests requests used in
* a document environment or it will throw an InvalidAccessError exception.
* When a timeout happens, a timeout event is fired.
*/
timeout?: StaticOrDynamic<number>;
/**
* The name of the file param that gets transferred.
*/
paramName?: ParamName;
/**
* The param name syntax for multiple uploads.
*
* **Options:**
* - `0 (Empty)` _(Default)_ Adds nothing to the paramName: `file`
* - `1 (Indexed)` Adds the array index of the file: `file[0]`
* - `2 (Brackets)` Adds the array-like brackets without index: `file[]`
*/
multipleParamNameStyle?: ParamNameStyle;
/**
* An object of additional parameters to transfer to the server.
* This is the same as adding hidden input fields in the form element.
*/
params?: StaticOrDynamic<Dictionary<string>>;
headers?: StaticOrDynamic<Dictionary<string>>;
/**
* The XMLHttpRequest.responseType property is an enumerated value that
* returns the type of response. It also lets the author change the response
* type. If an empty string is set as the value of responseType, the default
* value text will be used.
*
* Setting the value of responseType to "document" is ignored if done in a
* Worker environment. When setting responseType to a particular value,
* the author should make sure that the server is actually sending a response
* compatible to that format. If the server returns data that is not
* compatible to the responseType that was set, the value of response will be
* null. Also, setting responseType for synchronous requests will throw an
* InvalidAccessError exception.
*/
responseType?: StaticOrDynamic<XMLHttpRequestResponseType>;
/**
* responseParseFunc is a function that given an XMLHttpRequest
* returns a response object. Allows for custom response parsing.
*/
responseParseFunc?: (xhr: XMLHttpRequest) => T;
errUploadError?: (xhr: XMLHttpRequest) => string;
errUploadTimeout?: (xhr: XMLHttpRequest) => string;
renameFile?: (name: string) => string;
};
export type XHRUploadGroup = {
id: number;
files: VTransmitFile[];
xhr: XMLHttpRequest;
};
let group_id = 0;
export class XHRDriver<T = any> implements DriverInterface {
public context: VTransmitUploadContext;
public url: StaticOrDynamic<string>;
public method: StaticOrDynamic<string>;
public withCredentials: StaticOrDynamic<boolean>;
public timeout: StaticOrDynamic<number>;
public paramName: ParamName;
public multipleParamNameStyle: ParamNameStyle;
public params: StaticOrDynamic<Dictionary<string>>;
public headers: StaticOrDynamic<Dictionary<string>>;
public responseType: StaticOrDynamic<XMLHttpRequestResponseType>;
public errUploadError: (xhr: XMLHttpRequest) => string;
public errUploadTimeout: (xhr: XMLHttpRequest) => string;
public renameFile: (name: string) => string;
public responseParseFunc?: (xhr: XMLHttpRequest) => T;
private uploadGroups: { [key: number]: XHRUploadGroup } = Object.create(
null
);
constructor(context: VTransmitUploadContext, options: XHRDriverOptions<T>) {
let {
url,
method = "post",
withCredentials = false,
timeout = 0,
paramName = "file",
multipleParamNameStyle = ParamNameStyle.Empty,
params = Object.create(null),
headers = {
Accept: "application/json",
"Cache-Control": "no-cache",
"X-Requested-With": "XMLHttpRequest",
},
responseType = "json",
responseParseFunc,
errUploadError = (xhr: XMLHttpRequest) =>
`Error during upload: ${xhr.statusText} [${xhr.status}]`,
errUploadTimeout = (_xhr: XMLHttpRequest) =>
`Error during upload: the server timed out.`,
renameFile = (name: string) => name,
} = options;
if (!url) {
throw new TypeError(
`${
this.constructor.name
} requires a 'url' parameter. Supply a string or a function returning a string.`
);
}
this.context = context;
this.url = url;
this.method = method;
this.withCredentials = withCredentials;
this.timeout = timeout;
this.paramName = paramName;
this.multipleParamNameStyle = multipleParamNameStyle;
this.params = params;
this.headers = headers;
// @ts-ignore
this.responseType = responseType;
this.responseParseFunc = responseParseFunc;
this.errUploadError = errUploadError;
this.errUploadTimeout = errUploadTimeout;
this.renameFile = renameFile;
}
uploadFiles(files: VTransmitFile[]): Promise<UploadResult<T>> {
return new Promise(resolve => {
if (!this.url) {
return resolve({
ok: false,
err: {
type: ErrType.Any,
message: `Missing upload URL.`,
data: this.url,
},
});
}
const xhr = new XMLHttpRequest();
const updateProgress = this.handleUploadProgress(files);
const id = group_id++;
const params = resolveStaticOrDynamic(this.params, files);
const headers = resolveStaticOrDynamic(this.headers, files);
this.uploadGroups[id] = { id, xhr, files };
for (const file of files) {
file.driverData.groupID = id;
file.startProgress();
}
xhr.open(
resolveStaticOrDynamic(this.method, files),
resolveStaticOrDynamic(this.url, files),
true
);
// Setting the timeout after open because of IE11 issue:
// @link https://gitlab.com/meno/dropzone/issues/8
xhr.timeout = resolveStaticOrDynamic(this.timeout, files);
xhr.withCredentials = resolveStaticOrDynamic(
this.withCredentials,
files
);
xhr.responseType = resolveStaticOrDynamic(this.responseType, files);
xhr.addEventListener("error", () => {
this.rmGroup(id);
resolve({
ok: false,
err: {
type: ErrType.Any,
message: this.errUploadError(xhr),
data: xhr,
},
});
});
xhr.upload.addEventListener("progress", updateProgress);
xhr.addEventListener("timeout", () => {
this.rmGroup(id);
resolve({
ok: false,
err: {
type: ErrType.Timeout,
message: this.errUploadTimeout(xhr),
data: xhr,
},
});
});
xhr.addEventListener("load", () => {
if (
files[0].status === UploadStatuses.Canceled ||
xhr.readyState !== XMLHttpRequest.DONE
) {
return;
}
// The XHR is complete, so remove the group
this.rmGroup(id);
let response: T;
if (this.responseParseFunc) {
response = this.responseParseFunc(xhr);
} else {
response = xhr.response;
if (!xhr.responseType) {
let contentType = xhr.getResponseHeader("content-type");
if (
contentType &&
contentType.indexOf("application/json") > -1
) {
try {
response = JSON.parse(xhr.responseText);
} catch (err) {
return resolve({
ok: false,
err: {
message: "Invalid JSON response from server.",
type: ErrType.Any,
data: err,
},
});
}
}
}
}
// Called on load (complete) to complete progress tracking logic.
updateProgress();
if (xhr.status < 200 || xhr.status >= 300) {
return resolve({
ok: false,
err: {
type: ErrType.Any,
message: this.errUploadError(xhr),
data: xhr,
},
});
}
return resolve({
ok: true,
data: response,
});
});
for (const headerName of Object.keys(headers)) {
if (headers[headerName]) {
xhr.setRequestHeader(headerName, headers[headerName]);
}
}
const formData = new FormData();
for (const key of Object.keys(params)) {
formData.append(key, params[key]);
}
for (const file of files) {
this.context.emit(VTransmitEvents.Sending, file, xhr, formData);
}
if (this.context.props.uploadMultiple) {
this.context.emit(
VTransmitEvents.SendingMultiple,
files,
xhr,
formData
);
}
for (let i = 0, len = files.length; i < len; i++) {
formData.append(
this.getParamName(files[i], i),
files[i].nativeFile,
this.renameFile(files[i].name)
);
}
xhr.send(formData);
});
}
handleUploadProgress(files: VTransmitFile[]): (e?: ProgressEvent) => void {
const vm = this.context.vtransmit;
return function onProgressFn(e?: ProgressEvent): void {
if (!e) {
let allFilesFinished = true;
for (const file of files) {
if (
file.upload.progress !== 100 ||
file.upload.bytesSent !== file.upload.total
) {
allFilesFinished = false;
}
file.upload.progress = 100;
file.upload.bytesSent = file.upload.total;
file.endProgress();
}
if (allFilesFinished) {
return;
}
}
for (const file of files) {
if (e) {
file.handleProgress(e);
}
vm.$emit(
VTransmitEvents.UploadProgress,
file,
file.upload.progress,
file.upload.bytesSent
);
}
};
}
getParamName(file: VTransmitFile, index: string | number): string {
let paramName: string;
if (is_function(this.paramName)) {
paramName = this.paramName(file);
} else {
paramName = this.paramName;
}
if (!this.context.props.uploadMultiple) {
return paramName;
}
switch (this.multipleParamNameStyle) {
case ParamNameStyle.Indexed:
paramName += `[${index}]`;
break;
case ParamNameStyle.Brackets:
paramName += `[]`;
break;
case ParamNameStyle.Empty:
default:
break;
}
return paramName;
}
cancelUpload(file: VTransmitFile): VTransmitFile[] {
let group = this.uploadGroups[file.driverData.groupID];
if (!group) {
return [];
}
group.xhr.abort();
this.rmGroup(file.driverData.groupID);
return [...group.files];
}
rmGroup(id: number) {
delete this.uploadGroups[id];
}
}