-
Notifications
You must be signed in to change notification settings - Fork 1
/
etools-ajax.js
74 lines (64 loc) · 1.97 KB
/
etools-ajax.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
import {PolymerElement} from '@polymer/polymer/polymer-element.js';
import {Debouncer} from '@polymer/polymer/lib/utils/debounce.js';
import EtoolsAjaxRequestMixin from './etools-ajax-request-mixin.js';
import {timeOut} from '@polymer/polymer/lib/utils/async.js';
import {logError} from '@unicef-polymer/etools-behaviors/etools-logging';
/**
* @polymer
* @customElement
* @applies EtoolsAjaxRequestMixin
*/
class EtoolsAjax extends EtoolsAjaxRequestMixin(PolymerElement) {
static get is() {
return 'etools-ajax';
}
static get properties() {
return {
url: String,
method: String,
endpoint: Object,
params: Object,
body: Object
};
}
static get observers() {
return ['_optionsChanged(url)', '_optionsChanged(endpoint)', '_optionsChanged(params)', '_optionsChanged(method)'];
}
send() {
const opt = {
endpoint: this.endpoint || {url: this.url},
params: this.params,
method: this.method,
body: this.body
};
return this.sendRequest(opt)
.then((data) => {
this.dispatchEvent(new CustomEvent('success', {detail: data, bubbles: true, composed: true}));
return data;
})
.catch((error) => {
this.handleError(error);
});
}
_optionsChanged() {
this._debouncer = Debouncer.debounce(this._debouncer, timeOut.after(300), () => {
if (!this.endpoint && !this.url) {
return;
}
this.send();
});
}
handleError(error) {
if (error.status === 401) {
this.dispatchEvent(new CustomEvent('unauthorized', {detail: error.error, bubbles: true, composed: true}));
return;
}
if (error.status === 403) {
this.dispatchEvent(new CustomEvent('forbidden', {detail: error.error, bubbles: true, composed: true}));
return;
}
logError('error', error.error);
this.dispatchEvent(new CustomEvent('fail', {detail: error.error, bubbles: true, composed: true}));
}
}
customElements.define(EtoolsAjax.is, EtoolsAjax);