-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.js
104 lines (87 loc) · 2.26 KB
/
redis.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const REDIS_NAMESPACE = 'airnz-inspire';
const API_COLLECTIONS = {
'destinations':{
hasNestedEndpoints:true
},
'articles':{
hasNestedEndpoints:true
},
'settings':{
hasNestedEndpoints:false
},
'pages':{
hasNestedEndpoints:true
},
'navigation':{
hasNestedEndpoints:false
}
}
function fetchEndpoint(endpoint) {
return new Promise((resolve, reject) => {
request(url.resolve(app.locals.host, endpoint), (err, res) => {
if(res.statusCode == '404'){
reject('Not found');
}else{
resolve(res.body)
}
});
})
}
function fetchData(endpoint){
return new Promise((resolve, reject) => {
request(url.resolve(app.locals.host, endpoint), (err, res) => {
if(res.statusCode == '404' || err){
reject('Not found');
}else{
resolve(res.body)
}
});
})
}
function storeData(res){
let client = redis.createClient();
let finalEndpoints = [];
let nestedEndpoints = 0;
let nestedPromises = [];
let nestedPromiseCount = 0;
let finalAPIData = {};
_.each(API_COLLECTIONS, (coll, key) => {
// loop through and dive deeper into the ones which have children
nestedEndpoints++;
if(coll.hasNestedEndpoints){
nestedPromises[nestedPromiseCount] = fetchEndpoint(key).then((el) => {
let obj = JSON.parse(el);
obj.forEach((detail) => {
nestedEndpoints++;
// polyfill
let d = detail.detail.replace('pages', 'page');
finalEndpoints.push(d.replace(app.locals.host, ''));
});
})
nestedPromiseCount++;
}
finalEndpoints.push(key);
})
Promise.all(nestedPromises).then(() => {
_.each(finalEndpoints, (endpoint, key) => {
finalEndpoints[key] = fetchData(endpoint).then((data) => {
finalAPIData[endpoint] = JSON.parse(data);
}).catch((err) => {
console.log(err);
})
})
let count = 0;
Promise.all(finalEndpoints).then(() => {
app.locals.data = finalAPIData;
client.set(REDIS_NAMESPACE, JSON.stringify(finalAPIData),
(err) => {
if(err){
res.send("There's been an issue. Here it is:\n" + err);
}else{
res.send("Cache has been updated.")
}
client.quit();
});
})
})
}