Serializer.js 1.8 KB

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