@tsed/json-mapper
Version:
Json mapper module for Ts.ED Framework
306 lines (305 loc) • 13.5 kB
JavaScript
import { classOf, isArray, isBoolean, isEmpty, isNil, nameOf, objectKeys } from "@tsed/core";
import { getPropertiesStores, JsonEntityStore, JsonParameterStore, JsonSchema, VendorKeys } from "@tsed/schema";
import { alterAfterDeserialize } from "../hooks/alterAfterDeserialize.js";
import { alterBeforeDeserialize } from "../hooks/alterBeforeDeserialize.js";
import { alterOnDeserialize } from "../hooks/alterOnDeserialize.js";
import { JsonMapperCompiler } from "./JsonMapperCompiler.js";
import { JsonMapperSettings } from "./JsonMapperSettings.js";
import { getJsonMapperTypes } from "./JsonMapperTypesContainer.js";
import { Writer } from "./Writer.js";
function isDeserializable(obj, options) {
if ((!!options.collectionType && isNil(obj)) || obj === undefined) {
return false;
}
return !(isEmpty(options.type) || (options.type === Object && !options.collectionType));
}
function varKey(k) {
return `__${k}`;
}
function mapParamStoreOptions(store, options) {
return {
...options,
store: undefined,
type: store.getBestType(),
collectionType: store.collectionType,
groups: store.parameter.schema().getGroups(),
generics: store.parameter.schema().getGenericOf()
};
}
/**
* Deserializes raw JSON data into class instances based on schema metadata,
* handling collections, discriminators, hooks, and registered type mappers.
*/
export class JsonDeserializer extends JsonMapperCompiler {
constructor() {
super();
/**
* Cached classes by his id
* @protected
*/
this.constructors = {};
this.addGlobal("newInstanceOf", this.newInstanceOf.bind(this));
this.addGlobal("alterBeforeDeserialize", this.alterBeforeDeserialize.bind(this));
this.addGlobal("alterAfterDeserialize", this.alterAfterDeserialize.bind(this));
this.addGlobal("mapGenericsOptions", this.mapGenericsOptions.bind(this));
this.addTypeMapper(Object, this.mapObject.bind(this));
this.addTypeMapper(Array, this.mapArray.bind(this));
this.addTypeMapper(Map, this.mapMap.bind(this));
this.addTypeMapper(Set, this.mapSet.bind(this));
this.addTypeMapper("ObjectId", (value) => String(value));
}
map(input, options = {}) {
options = this.mapOptions(options);
if (!isDeserializable(input, options)) {
return input;
}
if (!options.collectionType && isArray(input)) {
options.collectionType = Array;
}
const model = options.type || classOf(input);
const mapper = this.compile(model, options.groups);
if (options.collectionType) {
const collectionMapper = this.compile(options.collectionType, options.groups);
return collectionMapper.fn(input, { ...options, id: mapper.id });
}
return mapper.fn(input, this.createContext(options));
}
compile(model, groups) {
if ([WeakMap, WeakSet].includes(model)) {
throw new Error(`${nameOf(model)} is not supported by JsonMapper.`);
}
return super.compile(model, groups);
}
compileMapper(mapper, { id, groupsId, model, storeGroups }) {
if (typeof model === "function") {
this.constructors[id] = model;
}
return super.compileMapper(mapper, { id, groupsId, model, storeGroups });
}
newInstanceOf(id, obj, options) {
try {
return new this.constructors[id](options.disableUnsecureConstructor ? {} : obj);
}
catch (er) {
return obj;
}
}
createMapper(model, id, groups) {
const entity = JsonEntityStore.from(model);
const properties = new Set();
const schemaProperties = [...getPropertiesStores(entity).values()];
const writer = new Writer().arrow("input", "options");
writer.if("isNil(input)").return("input");
if (entity.schema.hasDiscriminator) {
writer.add(this.mapDiscriminator(entity, groups));
}
// pre hook
if (entity.schema.$hooks?.has("beforeDeserialize")) {
this.schemes[id] = entity.schema;
writer.set("input", `alterBeforeDeserialize('${id}', input, options)`);
}
writer.set("options", "{...options, self: input}");
writer.const("obj", `newInstanceOf('${id}', input, options)`);
// properties
writer.add(...schemaProperties.flatMap((propertyStore) => {
const key = propertyStore.propertyName;
// TODO V8 add this line: properties.add(key as string);
properties.add(String(propertyStore.parent.schema.getAliasOf(key) || key));
if ((propertyStore.schema?.$ignore && isBoolean(propertyStore.schema?.$ignore)) ||
propertyStore.isGetterOnly() ||
(propertyStore.schema?.$hooks?.has("groups") && this.alterGroups(propertyStore.schema, groups))) {
return;
}
return this.mapProperty(propertyStore, id, groups);
}));
// additional properties
writer.add(this.mapAdditionalProperties(entity, properties, groups));
// post hook
if (entity.schema.$hooks?.has("afterDeserialize")) {
this.schemes[id] = entity.schema;
return writer.return(`alterAfterDeserialize('${id}', obj, options)`).root().toString();
}
return writer.return("obj").root().toString();
}
alterValue(schemaId, value, options) {
return alterOnDeserialize(this.schemes[schemaId], value, options);
}
mapDiscriminator(entity, groups) {
const writer = new Writer();
const discriminator = entity.schema.discriminator();
const sw = writer.switch(`input['${discriminator.propertyName}']`);
discriminator.values.forEach((value, kind) => {
const nestedMapper = this.compile(value, groups);
sw.case(`'${kind}'`).returnCallMapper(nestedMapper.id, "input");
});
return writer;
}
mapProperty(propertyStore, id, groups) {
const key = String(propertyStore.propertyKey);
const aliasKey = String(propertyStore.parent.schema.getAliasOf(key) || key);
const schemaId = this.getSchemaId(id, key);
const format = propertyStore.itemSchema.get("format");
const formatOpts = format && `options: {format: '${format}'}`;
let writer = new Writer().add(`// Map ${key} ${id} ${groups || ""}`);
const pick = key !== aliasKey ? `options.useAlias ? '${aliasKey}' : '${key}'` : `'${key}'`;
// ignore hook (deprecated)
if (propertyStore.schema?.$hooks?.has("ignore")) {
this.schemes[schemaId] = propertyStore.schema;
writer = writer.if(`!alterIgnore('${schemaId}', {...options, self: input})`);
}
// pre hook
const hasDeserializer = propertyStore.schema?.$hooks?.has("onDeserialize");
let getter = `input[${pick}]`;
if (hasDeserializer) {
this.schemes[schemaId] = propertyStore.schema;
const opts = Writer.options(formatOpts);
getter = `alterValue('${schemaId}', input[${pick}], ${opts})`;
}
const ifWriter = writer.set(`let ${varKey(key)}`, getter).if(`${varKey(key)} !== undefined`);
const fill = this.getPropertyFiller(propertyStore, id, groups, formatOpts);
if (hasDeserializer) {
fill(ifWriter.if(`${varKey(key)} === input.${key}`));
}
else {
fill(ifWriter);
}
ifWriter.set(`obj.${key}`, varKey(key));
if (groups && groups.includes("partial")) {
ifWriter.else().add(`delete obj.${key}`);
}
return writer.root();
}
getPropertyFiller(propertyStore, id, groups, formatOpts) {
const key = String(propertyStore.propertyKey);
const schemaId = this.getSchemaId(id, key);
if (propertyStore.itemSchema.isGeneric) {
const label = propertyStore.itemSchema.get(VendorKeys.GENERIC_LABEL);
return (writer) => {
const opts = Writer.options(formatOpts, `...mapGenericsOptions('${label}', options.generics)`);
return writer.set(varKey(key), `compileAndMap(${varKey(key)}, ${opts})`);
};
}
const type = propertyStore.itemSchema.hasDiscriminator ? propertyStore.itemSchema.discriminator().base : propertyStore.getBestType();
const nestedMapper = this.compile(type, groups);
if (propertyStore.isCollection) {
if (propertyStore.itemSchema.getGenericOf()) {
this.schemes[schemaId] = propertyStore.itemSchema;
return (writer) => {
return writer.callMapper(nameOf(propertyStore.collectionType), varKey(key), `id: '${nestedMapper.id}'`, `generics: schemes['${schemaId}'].getGenericOf()`, formatOpts);
};
}
return (writer) => writer.callMapper(nameOf(propertyStore.collectionType), varKey(key), `id: '${nestedMapper.id}'`, formatOpts);
}
if (propertyStore.schema.getGenericOf()) {
this.schemes[schemaId] = propertyStore.schema;
return (writer) => {
return writer.callMapper(nestedMapper.id, varKey(key), formatOpts, `generics: schemes['${schemaId}'].getGenericOf()`);
};
}
return (writer) => writer.callMapper(nestedMapper.id, varKey(key), formatOpts);
}
mapOptions({ groups, useAlias = true, types, ...options }) {
if (options.store instanceof JsonParameterStore) {
return this.mapOptions(mapParamStoreOptions(options.store, options));
}
const customMappers = {};
types = types || getJsonMapperTypes();
types.forEach((mapper, model) => {
if (![Array, Set, Map].includes(model)) {
const typeName = nameOf(model);
if (nameOf(model) in mapper) {
this.addTypeMapper(model, mapper[typeName].bind(mapper));
}
else {
this.addTypeMapper(model, (value, options) => mapper.deserialize(value, {
...options,
type: model
}));
}
}
});
const strictGroups = options.strictGroups ?? JsonMapperSettings.strictGroups;
return {
...options,
additionalProperties: options.additionalProperties ?? JsonMapperSettings.additionalProperties,
disableUnsecureConstructor: options.disableUnsecureConstructor ?? JsonMapperSettings.disableUnsecureConstructor,
groups: groups === undefined ? (strictGroups ? [] : false) : groups || false,
useAlias,
customMappers,
generics: options.generics || {}
};
}
mapAdditionalProperties(entity, properties, groups) {
const additionalProperties = entity.schema.get("additionalProperties");
const exclude = [...properties.values()].map((key) => `'${key}'`).join(", ");
const writer = new Writer();
writer.add("// add additional properties");
let each = writer.each("objectKeys(input)", ["key"]);
if (exclude.length) {
each = each.if(`![${exclude}].includes(key)`);
}
if (additionalProperties && additionalProperties instanceof JsonSchema) {
const nestedMapper = this.compile(additionalProperties.class, groups);
each.set("obj[key]", Writer.mapper(nestedMapper.id, "input[key]", "options"));
return writer;
}
if (additionalProperties) {
each.set("obj[key]", "input[key]");
return writer;
}
// dynamic additional properties options
each.if(`options.additionalProperties && obj[key] === undefined`).set("obj[key]", "input[key]");
return writer;
}
mapObject(input, options) {
return input;
}
mapSet(input, options) {
if (isNil(input)) {
return input;
}
const obj = new Set();
objectKeys(input).forEach((key) => {
obj.add(this.mapItem(input[key], options));
});
return obj;
}
mapArray(input, options) {
if (isNil(input)) {
return input;
}
return [].concat(input).map((item) => {
return this.mapItem(item, options);
});
}
mapMap(input, options) {
if (isNil(input)) {
return input;
}
const obj = new Map();
objectKeys(input).forEach((key) => {
obj.set(key, this.mapItem(input[key], options));
});
return obj;
}
mapItem(input, { id, ...options }) {
return this.execMapper(id, input, options);
}
alterBeforeDeserialize(schemaId, value, options) {
return alterBeforeDeserialize(value, this.schemes[schemaId], options);
}
alterAfterDeserialize(schemaId, value, options) {
return alterAfterDeserialize(value, this.schemes[schemaId], options);
}
mapGenericsOptions(label, inputGenerics) {
const generics = inputGenerics?.[label];
if (!generics) {
return {};
}
const type = generics[0] instanceof JsonSchema ? generics[0].getTarget() : generics[0];
return {
type,
generics: generics[1]
};
}
}