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