2018-12-26 05:07:51 +08:00
|
|
|
/*
|
|
|
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
|
|
|
*/
|
|
|
|
|
|
|
|
"use strict";
|
|
|
|
|
2023-05-23 02:32:23 +08:00
|
|
|
/** @typedef {import("./ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
|
|
|
|
/** @typedef {import("./ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
|
|
|
|
|
2018-12-26 05:07:51 +08:00
|
|
|
class NullPrototypeObjectSerializer {
|
2023-05-23 02:32:23 +08:00
|
|
|
/**
|
2024-06-11 21:09:50 +08:00
|
|
|
* @template {object} T
|
2023-05-23 02:32:23 +08:00
|
|
|
* @param {T} obj null object
|
|
|
|
* @param {ObjectSerializerContext} context context
|
|
|
|
*/
|
|
|
|
serialize(obj, context) {
|
|
|
|
/** @type {string[]} */
|
2018-12-26 05:07:51 +08:00
|
|
|
const keys = Object.keys(obj);
|
|
|
|
for (const key of keys) {
|
2023-05-23 02:32:23 +08:00
|
|
|
context.write(key);
|
2018-12-26 05:07:51 +08:00
|
|
|
}
|
2023-05-23 02:32:23 +08:00
|
|
|
context.write(null);
|
2018-12-26 05:07:51 +08:00
|
|
|
for (const key of keys) {
|
2024-08-09 01:03:17 +08:00
|
|
|
context.write(obj[/** @type {keyof T} */ (key)]);
|
2018-12-26 05:07:51 +08:00
|
|
|
}
|
|
|
|
}
|
2024-07-31 12:23:44 +08:00
|
|
|
|
2023-05-23 02:32:23 +08:00
|
|
|
/**
|
2024-06-11 21:09:50 +08:00
|
|
|
* @template {object} T
|
2023-05-23 02:32:23 +08:00
|
|
|
* @param {ObjectDeserializerContext} context context
|
|
|
|
* @returns {T} null object
|
|
|
|
*/
|
|
|
|
deserialize(context) {
|
|
|
|
/** @type {T} */
|
2018-12-26 05:07:51 +08:00
|
|
|
const obj = Object.create(null);
|
2023-05-23 02:32:23 +08:00
|
|
|
/** @type {string[]} */
|
2018-12-26 05:07:51 +08:00
|
|
|
const keys = [];
|
2023-05-23 02:32:23 +08:00
|
|
|
/** @type {string | null} */
|
|
|
|
let key = context.read();
|
2018-12-26 05:07:51 +08:00
|
|
|
while (key !== null) {
|
|
|
|
keys.push(key);
|
2023-05-23 02:32:23 +08:00
|
|
|
key = context.read();
|
2018-12-26 05:07:51 +08:00
|
|
|
}
|
|
|
|
for (const key of keys) {
|
2024-08-09 01:03:17 +08:00
|
|
|
obj[/** @type {keyof T} */ (key)] = context.read();
|
2018-12-26 05:07:51 +08:00
|
|
|
}
|
|
|
|
return obj;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = NullPrototypeObjectSerializer;
|