This repository has been archived by the owner on Mar 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
api.js
87 lines (70 loc) · 2.04 KB
/
api.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
82
83
84
85
86
87
import utils from '../utils';
function Api() {
this.data = [];
this.config = {};
}
Api.prototype.getUserData = function(target) {
if(!target) { return Promise.resolve({}); }
return fetch(target, {
timeout: 2000,
useCorsProxy: true,
credentials: 'include'
})
.then( res => res.json())
.catch(() => Promise.resolve({}));
};
Api.prototype.getPageData = function(target, timeout) {
if(!target) { return Promise.resolve({}); }
timeout = timeout || 2000;
return fetch(target, {
timeout: timeout,
useCorsProxy: true
})
.then( res => res.json())
.catch(() => Promise.resolve({}));
};
Api.prototype.handleResponse = function(response) {
utils.broadcast('adsAPIComplete');
this.data = response;
for(let i = 0; i < response.length; i++) {
const responseObj = response[i];
const keys = ['user', 'page'];
const kruxObj = {};
if(responseObj.krux && responseObj.krux.attributes) {
kruxObj[keys[i]] = this.instance.utils.buildObjectFromArray(responseObj.krux.attributes);
this.instance.krux.add(kruxObj);
}
if(responseObj.dfp && responseObj.dfp.targeting) {
this.instance.targeting.add(this.instance.utils.buildObjectFromArray(responseObj.dfp.targeting));
}
if(this.config.usePageZone && responseObj.dfp && responseObj.dfp.adUnit) {
const gpt = this.instance.config('gpt');
/* istanbul ignore else */
if(gpt && gpt.zone) {
gpt.zone = responseObj.dfp.adUnit.join('/');
}
}
}
return response;
};
Api.prototype.init = function(config, oAds) {
this.config = config;
this.instance = oAds;
if(!config) {
return Promise.resolve();
}
return Promise.all([this.getUserData(config.user), this.getPageData(config.page)])
.then(this.handleResponse.bind(this));
};
Api.prototype.reset = function() {
this.instance.krux.resetAttributes();
this.data.forEach(responseObj => {
if(responseObj.dfp && responseObj.dfp.targeting) {
responseObj.dfp.targeting.forEach(kv => {
this.instance.targeting.remove(kv.key);
this.instance.gpt.clearPageTargetingForKey(kv.key);
});
}
});
};
export default new Api();