-
Notifications
You must be signed in to change notification settings - Fork 1
/
etools-ajax-data-mixin.js
81 lines (73 loc) · 2.54 KB
/
etools-ajax-data-mixin.js
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
/* eslint-disable linebreak-style */
import {dedupingMixin} from '@polymer/polymer/lib/utils/mixin.js';
/* eslint-disable no-unused-vars */
/**
* @polymer
* @mixinFunction
*/
const EtoolsAjaxDataMixin = dedupingMixin(
(baseClass) =>
class extends baseClass {
/* eslint-enable no-unused-vars */
_prepareMultiPartFormData(inputBody, prepareMultipartData) {
if (inputBody instanceof FormData) {
return inputBody; // body is already a FromData object
}
let formBody = new FormData();
const keys = Object.keys(inputBody);
const self = this;
keys.forEach((key) => {
if (prepareMultipartData) {
formBody = self._prepareFormData(self, formBody, inputBody[key], key);
} else {
formBody.append(key, inputBody[key]);
}
});
return formBody;
}
_prepareFormData(self, body, data, key) {
if (Array.isArray(data)) {
if (data.length === 0) {
// empty array
body.append(key, []);
} else {
// not empty array
data.forEach((arrData, mainIndex) => {
const k = key + '[' + mainIndex + ']';
if (self._isSimpleObject(arrData)) {
// Object, not null
Object.keys(arrData).forEach((keyArrData) => {
body = self._prepareFormData(self, body, arrData[keyArrData], k + '[_obj][' + keyArrData + ']');
});
} else if (self._isFile(arrData)) {
// File or Blobs
body.append(k, arrData);
} else if (Array.isArray(arrData)) {
// Array
body = self._prepareFormData(self, body, arrData, k);
} else {
// strings, null, numbers
body.append(k, arrData);
}
});
}
} else if (self._isSimpleObject(data)) {
// Object, not null
Object.keys(data).forEach((keyArrData) => {
body = self._prepareFormData(self, body, data[keyArrData], key + '[_obj][' + keyArrData + ']');
});
} else {
// for Blob, File, strings, null vals
body.append(key, data);
}
return body;
}
_isFile(data) {
return data instanceof File || data instanceof Blob;
}
_isSimpleObject(data) {
return data !== null && typeof data === 'object' && !Array.isArray(data) && !this._isFile(data);
}
}
);
export default EtoolsAjaxDataMixin;