makeSerializable.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. * Defines the serializable class constructor type used by this module.
  12. * @template {SerializableClass} T
  13. * @typedef {(new (...params: EXPECTED_ANY[]) => T) & { deserialize?: (context: ObjectDeserializerContext) => T }} SerializableClassConstructor
  14. */
  15. /**
  16. * Represents ClassSerializer.
  17. * @template {SerializableClass} T
  18. */
  19. class ClassSerializer {
  20. /**
  21. * Creates an instance of ClassSerializer.
  22. * @param {SerializableClassConstructor<T>} Constructor constructor
  23. */
  24. constructor(Constructor) {
  25. this.Constructor = Constructor;
  26. }
  27. /**
  28. * Serializes this instance into the provided serializer context.
  29. * @param {T} obj obj
  30. * @param {ObjectSerializerContext} context context
  31. */
  32. serialize(obj, context) {
  33. obj.serialize(context);
  34. }
  35. /**
  36. * Restores this instance from the provided deserializer context.
  37. * @param {ObjectDeserializerContext} context context
  38. * @returns {T} obj
  39. */
  40. deserialize(context) {
  41. if (typeof this.Constructor.deserialize === "function") {
  42. return this.Constructor.deserialize(context);
  43. }
  44. const obj = new this.Constructor();
  45. obj.deserialize(context);
  46. return obj;
  47. }
  48. }
  49. /**
  50. * Processes the provided constructor.
  51. * @template {Constructor} T
  52. * @param {T} Constructor the constructor
  53. * @param {string} request the request which will be required when deserializing
  54. * @param {string | null=} name the name to make multiple serializer unique when sharing a request
  55. */
  56. module.exports = (Constructor, request, name = null) => {
  57. register(Constructor, request, name, new ClassSerializer(Constructor));
  58. };