-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (74 loc) · 2.11 KB
/
index.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
const {send} = require('micro')
const fetch = require('node-fetch')
const baseUrl = 'https://backend.b-works.io/'
const activeLanguages = ['de', 'en']
// Simple memory based caching
const cache = {}
/**
* GET /
* GET /?refresh
*/
module.exports = async (req, res) => {
if (/favicon.ico/.test(req.url)) {
return send(res, 404)
}
const startTime = Date.now()
// Check for cache buster flag
const refresh = /\brefresh\b/.test(req.url)
return {
queues: await getQueues(refresh),
contents: await getContents(refresh),
tags: await getTags(refresh),
time: Date.now() - startTime
}
}
async function getQueues (refresh) {
if (cache.queues && !refresh) {
return cache.queues
}
const request = await fetch(baseUrl + 'spa_api/contents_map?_format=json')
return cache.queues = request.json()
}
async function getContents (refresh) {
if (cache.contents && !refresh) {
return cache.contents
}
// See https://blog.lavrton.com/javascript-loops-how-to-handle-async-await-6252dd3c795
const promises = activeLanguages.map(getContentsTranslated)
const resolved = await Promise.all(promises)
// Convert array of objects back to objects
let contents = {}
resolved.forEach(obj => {
contents = {...contents, ...obj}
})
return cache.contents = contents
}
async function getContentsTranslated (lang) {
const request = await fetch(baseUrl + lang + '/spa_api/contents?_format=json')
const response = await request.json()
// Filter response
const contents = {}
contents[lang] = {}
Object.keys(response).forEach(key => {
const node = response[key]
if ('body' in node && node.body.length) {
delete node.body[0].processed
}
contents[lang][key] = node
})
return contents
}
async function getTags (refresh) {
if (cache.tags && !refresh) {
return cache.tags
}
const request = await fetch(baseUrl + 'spa_api/taxonomy_terms?_format=hal_json')
const response = await request.json()
// Filter response
const tags = {}
Object.keys(response).forEach(key => {
tags[key] = {}
tags[key].name = response[key].name
})
return cache.tags = tags
}