static.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. const range = require('koa-range');
  3. const compose = require('koa-compose');
  4. const staticCache = require('koa-static-cache');
  5. const assert = require('assert');
  6. const mkdirp = require('mkdirp');
  7. const LRU = require('ylru');
  8. const is = require('is-type-of');
  9. module.exports = (options, app) => {
  10. let dirs = options.dir;
  11. if (!is.array(dirs)) dirs = [ dirs ];
  12. const prefixs = [];
  13. function rangeMiddleware(ctx, next) {
  14. // if match static file, and use range middleware.
  15. const isMatch = prefixs.some(p => ctx.path.startsWith(p));
  16. if (isMatch) {
  17. return range(ctx, next);
  18. }
  19. return next();
  20. }
  21. const middlewares = [ rangeMiddleware ];
  22. for (const dirObj of dirs) {
  23. assert(is.object(dirObj) || is.string(dirObj), '`config.static.dir` must be `string | Array<string|object>`.');
  24. let newOptions;
  25. if (is.string(dirObj)) {
  26. // copy origin options to new options ensure the safety of objects
  27. newOptions = Object.assign({}, options, { dir: dirObj });
  28. } else {
  29. assert(is.string(dirObj.dir), '`config.static.dir` should contains `[].dir` property when object style.');
  30. newOptions = Object.assign({}, options, dirObj);
  31. }
  32. if (newOptions.dynamic && !newOptions.files) {
  33. newOptions.files = new LRU(newOptions.maxFiles);
  34. }
  35. if (newOptions.prefix) {
  36. prefixs.push(newOptions.prefix);
  37. }
  38. // ensure directory exists
  39. mkdirp.sync(newOptions.dir);
  40. app.loggers.coreLogger.info('[egg-static] starting static serve %s -> %s', newOptions.prefix, newOptions.dir);
  41. middlewares.push(staticCache(newOptions));
  42. }
  43. return compose(middlewares);
  44. };