makeSerializable.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const { register } = require("./serialization");
  6. /** @typedef {import("../serialization/ObjectMiddleware").Constructor} Constructor */
  7. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  8. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  9. /** @typedef {{ serialize: (context: ObjectSerializerContext) => void, deserialize: (context: ObjectDeserializerContext) => void }} SerializableClass */
  10. /**
  11. * @template {SerializableClass} T
  12. * @typedef {(new (...params: any[]) => T) & { deserialize?: (context: ObjectDeserializerContext) => T }} SerializableClassConstructor
  13. */
  14. /**
  15. * @template {SerializableClass} T
  16. */
  17. class ClassSerializer {
  18. /**
  19. * @param {SerializableClassConstructor<T>} Constructor constructor
  20. */
  21. constructor(Constructor) {
  22. this.Constructor = Constructor;
  23. }
  24. /**
  25. * @param {T} obj obj
  26. * @param {ObjectSerializerContext} context context
  27. */
  28. serialize(obj, context) {
  29. obj.serialize(context);
  30. }
  31. /**
  32. * @param {ObjectDeserializerContext} context context
  33. * @returns {T} obj
  34. */
  35. deserialize(context) {
  36. if (typeof this.Constructor.deserialize === "function") {
  37. return this.Constructor.deserialize(context);
  38. }
  39. const obj = new this.Constructor();
  40. obj.deserialize(context);
  41. return obj;
  42. }
  43. }
  44. /**
  45. * @template {Constructor} T
  46. * @param {T} Constructor the constructor
  47. * @param {string} request the request which will be required when deserializing
  48. * @param {string | null} [name] the name to make multiple serializer unique when sharing a request
  49. */
  50. module.exports = (Constructor, request, name = null) => {
  51. register(Constructor, request, name, new ClassSerializer(Constructor));
  52. };