Guest User

Untitled

a guest
Jun 25th, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. const ts = require('typescript');
  2. const crypto = require('crypto');
  3. const scriptCache = {};
  4. module.exports = function() {
  5. let originalCompiler = null;
  6.  
  7. const tsCompiler = (script, cb) => {
  8. const hash = crypto
  9. .createHash('md5')
  10. .update(script)
  11. .digest('hex');
  12. if (!scriptCache[hash]) {
  13. script = ts.transpileModule(script, {
  14. compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES5 }
  15. }).outputText;
  16. console.log(`Compiled code with has ${hash} to: \n${script}`);
  17. originalCompiler(script, cb);
  18. scriptCache[hash] = script;
  19. } else {
  20. console.log('Using ts cache');
  21. originalCompiler(scriptCache[hash], cb);
  22. }
  23. };
  24. return function(req, res, next) {
  25. console.log('I have middleware');
  26. const { compiler } = req.webtaskContext;
  27. if (originalCompiler === null && compiler.nodejsCompiler) {
  28. originalCompiler = compiler.nodejsCompiler;
  29. }
  30. compiler.nodejsCompiler = tsCompiler;
  31. return next();
  32. };
  33. };
Add Comment
Please, Sign In to add comment