123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193 |
- "use strict";
- const memoize = require("../util/memoize");
- const LAZY_TARGET = Symbol("lazy serialization target");
- const LAZY_SERIALIZED_VALUE = Symbol("lazy serialization data");
- class SerializerMiddleware {
-
-
- serialize(data, context) {
- const AbstractMethodError = require("../AbstractMethodError");
- throw new AbstractMethodError();
- }
-
-
- deserialize(data, context) {
- const AbstractMethodError = require("../AbstractMethodError");
- throw new AbstractMethodError();
- }
-
- static createLazy(value, target, options = {}, serializedValue = undefined) {
- if (SerializerMiddleware.isLazy(value, target)) return value;
- const fn =
-
- (typeof value === "function" ? value : () => value);
- fn[LAZY_TARGET] = target;
- fn.options = options;
- fn[LAZY_SERIALIZED_VALUE] = serializedValue;
- return fn;
- }
-
- static isLazy(fn, target) {
- if (typeof fn !== "function") return false;
- const t = fn[LAZY_TARGET];
- return target ? t === target : Boolean(t);
- }
-
- static getLazyOptions(fn) {
- if (typeof fn !== "function") return;
- return (fn).options;
- }
-
- static getLazySerializedValue(fn) {
- if (typeof fn !== "function") return;
- return fn[LAZY_SERIALIZED_VALUE];
- }
-
- static setLazySerializedValue(fn, value) {
- fn[LAZY_SERIALIZED_VALUE] = value;
- }
-
- static serializeLazy(lazy, serialize) {
- const fn = (
- memoize(() => {
- const r = lazy();
- if (
- r &&
- typeof ( (r).then) === "function"
- ) {
- return (
-
- (r).then(data => data && serialize(data))
- );
- }
- return serialize( (r));
- })
- );
- fn[LAZY_TARGET] = lazy[LAZY_TARGET];
- fn.options = lazy.options;
- lazy[LAZY_SERIALIZED_VALUE] = fn;
- return fn;
- }
-
- static deserializeLazy(lazy, deserialize) {
- const fn = (
- memoize(() => {
- const r = lazy();
- if (
- r &&
- typeof ( (r).then) === "function"
- ) {
- return (
-
- (r).then(data => deserialize(data))
- );
- }
- return deserialize( (r));
- })
- );
- fn[LAZY_TARGET] = lazy[LAZY_TARGET];
- fn.options = lazy.options;
- fn[LAZY_SERIALIZED_VALUE] = lazy;
- return fn;
- }
-
- static unMemoizeLazy(lazy) {
- if (!SerializerMiddleware.isLazy(lazy)) return lazy;
-
- const fn = () => {
- throw new Error(
- "A lazy value that has been unmemorized can't be called again"
- );
- };
- fn[LAZY_SERIALIZED_VALUE] = SerializerMiddleware.unMemoizeLazy(
- lazy[LAZY_SERIALIZED_VALUE]
- );
- fn[LAZY_TARGET] = lazy[LAZY_TARGET];
- fn.options = lazy.options;
- return fn;
- }
- }
- module.exports = SerializerMiddleware;
|