makeSerializable.js 968 B

12345678910111213141516171819202122232425262728293031323334353637
  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. class ClassSerializer {
  8. constructor(Constructor) {
  9. this.Constructor = Constructor;
  10. }
  11. serialize(obj, context) {
  12. obj.serialize(context);
  13. }
  14. deserialize(context) {
  15. if (typeof this.Constructor.deserialize === "function") {
  16. return this.Constructor.deserialize(context);
  17. }
  18. const obj = new this.Constructor();
  19. obj.deserialize(context);
  20. return obj;
  21. }
  22. }
  23. /**
  24. * @param {Constructor} Constructor the constructor
  25. * @param {string} request the request which will be required when deserializing
  26. * @param {string | null} [name] the name to make multiple serializer unique when sharing a request
  27. */
  28. module.exports = (Constructor, request, name = null) => {
  29. register(Constructor, request, name, new ClassSerializer(Constructor));
  30. };