-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathroutes.js
73 lines (63 loc) · 2.29 KB
/
routes.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
const url = require('url')
const mime = require('mime-types')
const router = require('express').Router()
const IPFSUtil = require('../utils/ipfs')
const RouteUtil = require('../utils/route')
const UrlUtil = require('../utils/url')
module.exports = (node) => {
router.get('/*', (req, res) => {
const reqPath = url.parse(req.originalUrl).pathname
IPFSUtil.resolveMultihashForLeafNode(node, reqPath)
.then((data) => {
node
.files
.cat(data.multihash)
.then((stream) => {
if (reqPath[reqPath.length - 1] === '/') {
RouteUtil.permanentRedirect(res, reqPath.substring(0, reqPath.length - 1))
} else {
const mimeType = mime.lookup(reqPath)
if (mimeType) {
res.set('Content-Type', mime.contentType(mimeType))
}
stream.pipe(res)
}
})
.catch((e) => {
if (e.toString() === 'Error: This dag node is a directory') {
IPFSUtil
.checkForDir(node, reqPath, data.multihash)
.then((data) => {
if (typeof data === 'string') {
if (reqPath[reqPath.length - 1] !== '/') {
RouteUtil.permanentRedirect(res, `${reqPath}/`)
} else {
res.send(data)
}
} else {
RouteUtil.permanentRedirect(res, UrlUtil.joinURLParts(reqPath, data[0].name))
}
}).catch((e) => {
console.error(e)
RouteUtil.somethingWentWrong(res)
})
} else {
console.error(e)
RouteUtil.somethingWentWrong(res)
}
})
}).catch((e) => {
const errorToString = e.toString()
if (errorToString === 'Error: Next file not found') {
res.status(404).send('404 File not found')
} else if (errorToString.indexOf('Error: multihash length inconsistent') !== -1 ||
errorToString === 'Error: Non-base58 character') {
res.status(400).send('400 Invalid multihash')
} else {
console.error(e)
RouteUtil.somethingWentWrong(res)
}
})
})
return router
}