-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
50 lines (46 loc) · 1.22 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
const fetchZone = require('./fetch-zone');
const { Zone, wire: { types, codes } } = require('bns');
const empty = new Zone()
function middleware () {
const zones = new Map()
const add = (cid) => {
let zone = zones.get(cid)
if (zone) {
return zone
}
const promise = new Promise((resolve, reject) => {
fetchZone(cid).then(zone => {
if (zone) {
zones.set(cid, zone)
resolve(zone)
} else {
// No cache + Servfail until swarm is ready
zones.delete(cid)
resolve(new Promise(res => res))
}
}).catch(reject)
})
zones.set(cid, promise)
return promise
}
return {
hostname: ':data.:protocol(_ipfs).:gateway?.',
handler: async ({ protocol, data }, name, type) => {
data = data.split('.')
const cid = data[data.length - 1]
try {
const zone = add(cid)
if (!(zone instanceof Promise)) {
return zone.resolve(name, types[type])
} else {
const res = empty.resolve(name, types[type])
res.code = codes.SERVFAIL // ensure response not cached
return res
}
} catch (e) {
return null
}
}
}
}
module.exports = middleware