@tsed/json-mapper
Version:
Json mapper module for Ts.ED Framework
291 lines • 12.9 kB
JavaScript
import { classOf, isArray, isBoolean, isClass, isEmpty, isNil, nameOf, objectKeys } from "@tsed/core";
import { getPropertiesStores, JsonEntityStore, JsonParameterStore } 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.groups,
// genericTypes: store.nestedGenerics[0],
generics: store.nestedGenerics
};
}
function getGenericIndex(propertyStore) {
return propertyStore.parent.schema.genericLabels.indexOf(propertyStore.itemSchema.genericType);
}
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.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);
}
eval(mapper, { id, groupsId, model }) {
this.constructors[id] = model;
return super.eval(mapper, { id, groupsId, model });
}
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)`);
}
// generics and options
writer.const("generics", "options.generics[0]");
if (entity.schema.genericLabels?.length) {
writer.set("options", "{...options, self: input, generics: [...options.generics].slice(1)}");
}
else {
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);
const generics = propertyStore.itemSchema.nestedGenerics;
const isGeneric = propertyStore.itemSchema.isGeneric && !generics?.length;
if (isGeneric) {
const index = getGenericIndex(propertyStore);
const opts = Writer.options(formatOpts, `type: generics[${index}]`);
return (writer) => 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) {
return (writer) => writer.callMapper(nameOf(propertyStore.collectionType), varKey(key), `id: '${nestedMapper.id}'`, formatOpts);
}
if (generics?.length) {
this.schemes[schemaId] = propertyStore.schema;
return (writer) => writer.callMapper(nestedMapper.id, varKey(key), formatOpts, `generics: schemes['${schemaId}'].nestedGenerics`);
}
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 (isClass(additionalProperties)) {
const nestedMapper = this.compile(additionalProperties.getComputedType(), 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);
}
}
//# sourceMappingURL=JsonDeserializer.js.map