makeSerializable.js 2.0 KB

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