This repository has been archived by the owner on Jul 11, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (41 loc) · 1.4 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
const path = require('path');
const url = require('url');
const mime = require('mime-types');
const fs = require('fs');
function middleware (opts = {}) {
const options = Object.assign({
manifest: 'push_manifest.json',
root: '.'
}, opts);
const manifest = require(path.resolve(options.root, options.manifest));
return function (ctx, next) {
const { host, protocol, res, req } = ctx;
if (req.url !== '/') return next();
function push (key) {
const popts = {
request: {
accept: '*/*'
},
response: {
'server': 'koa-h2-man-push',
'content-type': mime.lookup(key)
}
};
const p = ctx.res.push(key, popts);
const content = fs.createReadStream(path.resolve(options.root, key.slice(1)));
content.pipe(p);
p.on('error', console.error);
return p;
}
const links = Object.keys(manifest).map(key => {
const type = manifest[key].type;
const u = url.resolve(`${protocol}://${host}`, key);
return `<${u}>; rel=preload; as=${type}`;
});
ctx.set('Link', links.join(', '));
return next().then(() => {
Object.keys(manifest).forEach(push);
});
}
}
module.exports = middleware;