This repository was archived by the owner on Nov 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
74 lines (67 loc) · 2.19 KB
/
index.ts
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
import IPFS from 'ipfs-core';
import express, { Response, Request, NextFunction } from 'express';
import all from 'it-all';
import mime from 'mime-types';
IPFS.create().then(async ipfs => {
const app = express();
const sendByCid = async (cid: string, filename: string, res: Response) => {
res.set({
'Content-Type': mime.lookup(filename) || 'application/octet-stream',
'Content-Disposition': `inline; filename="${filename}"`,
'Cache-Control': 'public, max-age=31536000, immutable, only-if-cached'
});
res.send(Buffer.concat(await all(ipfs.cat(cid))));
}
app.get('/ipfs/connect/:path(*)', async (req, res, next) => {
try {
await ipfs.swarm.connect(IPFS.multiaddr(`/${req.params.path}`));
res.status(200).send({ connected: true });
}
catch (error) {
next(error)
}
});
app.get('/ipfs/file/:cid/:filename', async (req, res, next) => {
try {
const { cid, filename } = req.params;
await sendByCid(cid, filename, res);
}
catch(error) {
next(error);
}
});
app.get('/ipfs/:path(*)', async (req, res, next) => {
try {
const cid = decodeURIComponent(req.params.path);
const items = await all(ipfs.ls(cid));
if (items.length > 1) {
const returns: {[keyof: string]: string} = {};
for (const item of items) {
const [path, ...filename] = item.path.split('/');
returns[item.name] = `${path}/${filename.map(encodeURIComponent).join('/')}`;
}
res.send(returns);
} else {
const filename = req.query.filename?.toString() || items[0].name;
await sendByCid(cid, filename, res);
}
}
catch (error) {
next(error);
}
});
app.get('/*', (req, res) => {
let query = '';
const { filename } = req.query;
if (req.query.filename) {
query = `?filename=${filename}`
}
res.redirect('/ipfs' + req.path + query);
})
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
const status = err.message === 'ERR_NOT_FOUND' ? 404 : 500
res.status(status).send(err);
});
const PORT = process.env.APP_PORT || 4000;
app.listen(PORT, () => console.log(`online at port ${PORT}`));
});