Serializer.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. /**
  6. * @template T, K
  7. * @typedef {import("./SerializerMiddleware")<T, K>} SerializerMiddleware
  8. */
  9. class Serializer {
  10. /**
  11. * @param {SerializerMiddleware<any, any>[]} middlewares serializer middlewares
  12. * @param {TODO=} context context
  13. */
  14. constructor(middlewares, context) {
  15. this.serializeMiddlewares = middlewares.slice();
  16. this.deserializeMiddlewares = middlewares.slice().reverse();
  17. this.context = context;
  18. }
  19. /**
  20. * @param {any} obj object
  21. * @param {TODO} context content
  22. * @returns {Promise<any>} result
  23. */
  24. serialize(obj, context) {
  25. const ctx = { ...context, ...this.context };
  26. let current = obj;
  27. for (const middleware of this.serializeMiddlewares) {
  28. if (current && typeof current.then === "function") {
  29. current = current.then(data => data && middleware.serialize(data, ctx));
  30. } else if (current) {
  31. try {
  32. current = middleware.serialize(current, ctx);
  33. } catch (err) {
  34. current = Promise.reject(err);
  35. }
  36. } else break;
  37. }
  38. return current;
  39. }
  40. /**
  41. * @param {any} value value
  42. * @param {TODO} context context
  43. * @returns {Promise<any>} result
  44. */
  45. deserialize(value, context) {
  46. const ctx = { ...context, ...this.context };
  47. /** @type {any} */
  48. let current = value;
  49. for (const middleware of this.deserializeMiddlewares) {
  50. if (current && typeof current.then === "function") {
  51. current = current.then(data => middleware.deserialize(data, ctx));
  52. } else {
  53. current = middleware.deserialize(current, ctx);
  54. }
  55. }
  56. return current;
  57. }
  58. }
  59. module.exports = Serializer;