Last change
on this file since 6c1585f was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
1.2 KB
|
Rev | Line | |
---|
[6a3a178] | 1 | /*
|
---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
| 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(
|
---|
| 20 | data => data && middleware.serialize(data, context)
|
---|
| 21 | );
|
---|
| 22 | } else if (current) {
|
---|
| 23 | try {
|
---|
| 24 | current = middleware.serialize(current, ctx);
|
---|
| 25 | } catch (err) {
|
---|
| 26 | current = Promise.reject(err);
|
---|
| 27 | }
|
---|
| 28 | } else break;
|
---|
| 29 | }
|
---|
| 30 | return current;
|
---|
| 31 | }
|
---|
| 32 |
|
---|
| 33 | deserialize(value, context) {
|
---|
| 34 | const ctx = { ...context, ...this.context };
|
---|
| 35 | /** @type {any} */
|
---|
| 36 | let current = value;
|
---|
| 37 | for (const middleware of this.deserializeMiddlewares) {
|
---|
| 38 | if (current && typeof current.then === "function") {
|
---|
| 39 | current = current.then(data => middleware.deserialize(data, context));
|
---|
| 40 | } else {
|
---|
| 41 | current = middleware.deserialize(current, ctx);
|
---|
| 42 | }
|
---|
| 43 | }
|
---|
| 44 | return current;
|
---|
| 45 | }
|
---|
| 46 | }
|
---|
| 47 |
|
---|
| 48 | module.exports = Serializer;
|
---|
Note:
See
TracBrowser
for help on using the repository browser.