1 |
|
2 |
|
3 |
|
4 |
|
5 | "use strict";
|
6 |
|
7 | class Serializer {
|
8 | constructor(middlewares, context) {
|
9 | this.serializeMiddlewares = middlewares.slice();
|
10 | this.deserializeMiddlewares = middlewares.slice().reverse();
|
11 | this.context = context;
|
12 | }
|
13 |
|
14 | serialize(obj, context) {
|
15 | const ctx = { ...context, ...this.context };
|
16 | let current = obj;
|
17 | for (const middleware of this.serializeMiddlewares) {
|
18 | if (current && typeof current.then === "function") {
|
19 | current = current.then(data => data && middleware.serialize(data, ctx));
|
20 | } else if (current) {
|
21 | try {
|
22 | current = middleware.serialize(current, ctx);
|
23 | } catch (err) {
|
24 | current = Promise.reject(err);
|
25 | }
|
26 | } else break;
|
27 | }
|
28 | return current;
|
29 | }
|
30 |
|
31 | deserialize(value, context) {
|
32 | const ctx = { ...context, ...this.context };
|
33 |
|
34 | let current = value;
|
35 | for (const middleware of this.deserializeMiddlewares) {
|
36 | if (current && typeof current.then === "function") {
|
37 | current = current.then(data => middleware.deserialize(data, ctx));
|
38 | } else {
|
39 | current = middleware.deserialize(current, ctx);
|
40 | }
|
41 | }
|
42 | return current;
|
43 | }
|
44 | }
|
45 |
|
46 | module.exports = Serializer;
|