Serializer.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. class Serializer {
  6. constructor(middlewares, context) {
  7. this.serializeMiddlewares = middlewares.slice();
  8. this.deserializeMiddlewares = middlewares.slice().reverse();
  9. this.context = context;
  10. }
  11. serialize(obj, context) {
  12. const ctx = { ...context, ...this.context };
  13. let current = obj;
  14. for (const middleware of this.serializeMiddlewares) {
  15. if (current && typeof current.then === "function") {
  16. current = current.then(data => data && middleware.serialize(data, ctx));
  17. } else if (current) {
  18. try {
  19. current = middleware.serialize(current, ctx);
  20. } catch (err) {
  21. current = Promise.reject(err);
  22. }
  23. } else break;
  24. }
  25. return current;
  26. }
  27. deserialize(value, context) {
  28. const ctx = { ...context, ...this.context };
  29. /** @type {any} */
  30. let current = value;
  31. for (const middleware of this.deserializeMiddlewares) {
  32. if (current && typeof current.then === "function") {
  33. current = current.then(data => middleware.deserialize(data, ctx));
  34. } else {
  35. current = middleware.deserialize(current, ctx);
  36. }
  37. }
  38. return current;
  39. }
  40. }
  41. module.exports = Serializer;