-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (46 loc) · 1.3 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
const { flatten, unflatten } = require('safe-flat')
const isUrl = require('is-url-superb')
class StrapiCdnUrlRewrite {
constructor(storageUrl, cdnUrl) {
if (storageUrl && isUrl(storageUrl) && cdnUrl && isUrl(cdnUrl)) {
this.storage = storageUrl
this.cdn = cdnUrl
} else if (
process.env.CDN_ENDPOINT &&
isUrl(process.env.CDN_ENDPOINT) &&
process.env.STORAGE_ENDPOINT &&
isUrl(process.env.STORAGE_ENDPOINT)
) {
this.storage = process.env.STORAGE_ENDPOINT
this.cdn = process.env.CDN_ENDPOINT
} else {
throw new Error('`storageUrl` and `cdnUrl` must be valid URLs')
}
}
crawl = data => {
const flattened = flatten(data)
for (let prop in flattened) {
if (typeof flattened[prop] === 'string' && flattened[prop].startsWith(this.storage)) {
flattened[prop] = flattened[prop].replace(this.storage, this.cdn)
}
}
return unflatten(flattened)
}
cdnRewrite = async data => {
try {
data = await data
if (Array.isArray(data)) {
let out = []
for (let item of data) {
out.push(this.crawl(await item))
}
return out
} else {
return this.crawl(data)
}
} catch (err) {
console.error(err)
}
}
}
module.exports = StrapiCdnUrlRewrite