webpack/lib/serialization/Serializer.js

70 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-10-09 20:30:59 +08:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
2025-03-07 21:12:22 +08:00
/** @typedef {import("./SerializerMiddleware").Context} Context */
2024-03-18 01:15:44 +08:00
/**
* @template T, K
* @typedef {import("./SerializerMiddleware")<T, K>} SerializerMiddleware
*/
2018-10-09 20:30:59 +08:00
class Serializer {
2024-03-18 01:15:44 +08:00
/**
* @param {SerializerMiddleware<any, any>[]} middlewares serializer middlewares
2025-03-07 21:12:22 +08:00
* @param {Context} [context] context
2024-03-18 01:15:44 +08:00
*/
constructor(middlewares, context) {
this.serializeMiddlewares = middlewares.slice();
this.deserializeMiddlewares = middlewares.slice().reverse();
this.context = context;
2018-10-09 20:30:59 +08:00
}
2024-03-18 01:15:44 +08:00
/**
2025-03-11 08:28:01 +08:00
* @param {TODO | Promise<TODO>} obj object
2025-03-07 21:12:22 +08:00
* @param {Context} context context object
2025-03-11 08:28:01 +08:00
* @returns {Promise<TODO>} result
2024-03-18 01:15:44 +08:00
*/
serialize(obj, context) {
const ctx = { ...context, ...this.context };
let current = obj;
for (const middleware of this.serializeMiddlewares) {
2021-06-18 16:21:19 +08:00
if (current && typeof current.then === "function") {
2025-03-11 08:28:01 +08:00
current =
/** @type {Promise<TODO>} */
(current).then(data => data && middleware.serialize(data, ctx));
} else if (current) {
try {
current = middleware.serialize(current, ctx);
} catch (err) {
current = Promise.reject(err);
}
} else break;
}
return current;
2018-10-09 20:30:59 +08:00
}
2024-03-18 01:15:44 +08:00
/**
2025-03-11 08:28:01 +08:00
* @param {TODO | Promise<TODO>} value value
2025-03-07 21:12:22 +08:00
* @param {Context} context object
2025-03-11 08:28:01 +08:00
* @returns {Promise<TODO>} result
2024-03-18 01:15:44 +08:00
*/
deserialize(value, context) {
const ctx = { ...context, ...this.context };
let current = value;
for (const middleware of this.deserializeMiddlewares) {
2024-08-02 02:36:27 +08:00
current =
current && typeof current.then === "function"
2025-03-11 08:28:01 +08:00
? /** @type {Promise<TODO>} */ (current).then(data =>
middleware.deserialize(data, ctx)
)
2024-08-02 02:36:27 +08:00
: middleware.deserialize(current, ctx);
}
return current;
2018-10-09 20:30:59 +08:00
}
}
module.exports = Serializer;