locals.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. const { Cache } = require('hexo-util');
  3. class Locals {
  4. constructor() {
  5. this.cache = new Cache();
  6. this.getters = {};
  7. }
  8. get(name) {
  9. if (typeof name !== 'string') throw new TypeError('name must be a string!');
  10. return this.cache.apply(name, () => {
  11. const getter = this.getters[name];
  12. if (!getter) return;
  13. return getter();
  14. });
  15. }
  16. set(name, value) {
  17. if (typeof name !== 'string') throw new TypeError('name must be a string!');
  18. if (value == null) throw new TypeError('value is required!');
  19. const getter = typeof value === 'function' ? value : () => value;
  20. this.getters[name] = getter;
  21. this.cache.del(name);
  22. return this;
  23. }
  24. remove(name) {
  25. if (typeof name !== 'string') throw new TypeError('name must be a string!');
  26. this.getters[name] = null;
  27. this.cache.del(name);
  28. return this;
  29. }
  30. invalidate() {
  31. this.cache.flush();
  32. return this;
  33. }
  34. toObject() {
  35. const result = {};
  36. const keys = Object.keys(this.getters);
  37. for (let i = 0, len = keys.length; i < len; i++) {
  38. const key = keys[i];
  39. const item = this.get(key);
  40. if (item != null) result[key] = item;
  41. }
  42. return result;
  43. }
  44. }
  45. module.exports = Locals;