bennyp

Untitled

Apr 9th, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const path = require('path');
  2. const url = require('url');
  3. const fs = require('fs');
  4.  
  5. const isFile = stat => stat.isFile();
  6. const readFile = file => () => fs.readFile(file);
  7.  
  8. const parseToString = file =>
  9.   JSON.parse(file.toString());
  10.  
  11. const pushUrl = ctx => key =>
  12.   url.resolve(`${ctx.protocol}://${ctx.host}`, key);
  13.  
  14. const link = (data, contents) => (key, i) =>
  15.   `<${contents[i]}>; rel=preload; as=${data[key].type}`;
  16.  
  17. const prepareH2Push = ctx => data => {
  18.   const keys = Object.keys(data);
  19.   const contents = keys.map(pushUrl(ctx));
  20.   const links = keys.map(link(data, contents));
  21.   return { contents, data, links };
  22. };
  23.  
  24. const push = (ctx, { singleHeader }) => ({ contents, data, links }) => {
  25.   if ( contents.length > 0 ) return;
  26.   ctx.set('Link', singleHeader ? links.join(', ') : links);
  27.   ctx.state.h2push = { contents, data, links };
  28. };
  29.  
  30. const trace = tag => m => (console.log(tag, m), m);
  31.  
  32. module.exports = MiddlewareBase => class PushMiddleware extends MiddlewareBase {
  33.   optionDefinitions() {
  34.     return [
  35.       { name: 'pushManifest', type: String, description: 'name of push manifest file' },
  36.     ];
  37.   }
  38.  
  39.   middleware({ singleHeader, pushManifest = 'push_manifest.json' }) {
  40.     return (ctx, next) => next().then(() => {
  41.  
  42.         if (!ctx.response.is('html')) return;
  43.         if ('nopush' in ctx.query) return;
  44.  
  45.         const manifest = path.resolve(path.dirname(ctx.body.path), pushManifest);
  46.         return fs.stat(manifest)
  47.           .then(trace('man'))
  48.           .then(isFile)
  49.           .then(trace('isFile'))
  50.           .then(readFile(manifest))
  51.           .then(parseToString)
  52.           .then(trace('parseToString'))
  53.           .then(prepareH2Push)
  54.           .then(push(ctx, { singleHeader }));
  55.       }
  56.     );
  57.   }
  58. };
Advertisement
Add Comment
Please, Sign In to add comment