UNPKG

@tsed/json-mapper

Version:
63 lines (62 loc) 1.77 kB
import { __decorate } from "tslib"; import { nameOf } from "@tsed/core"; import { JsonMapper } from "../decorators/jsonMapper.js"; function isNullish(data) { return [null, "null"].includes(data); } /** * Error thrown when a primitive conversion cannot be performed safely. */ export class CastError extends Error { constructor(message) { super(`Cast error. ${message}`); this.name = "CAST_ERROR"; } } /** * Mapper for the `String`, `Number`, `BigInt` and `Boolean` types. * @jsonmapper * @component */ let PrimitiveMapper = class PrimitiveMapper { deserialize(data, ctx) { return this[nameOf(ctx.type)] ? this[nameOf(ctx.type)](data, ctx) : undefined; } serialize(object, ctx) { return this[nameOf(ctx?.type)] && typeof object !== "object" ? this[nameOf(ctx.type)](object, ctx) : object; } String(data) { return data === null ? null : "" + data; } Boolean(data) { if (["true", "1", true].includes(data)) return true; if (["false", "0", false].includes(data)) return false; if (isNullish(data)) return null; if (data === undefined) return undefined; return !!data; } Number(data) { if (isNullish(data)) return null; if (data === undefined) return data; const n = +data; if (isNaN(n)) { throw new CastError("Expression value is not a number."); } return n; } BigInt(data) { if (isNullish(data)) return null; return BigInt(data); } }; PrimitiveMapper = __decorate([ JsonMapper(String, Number, Boolean, BigInt) ], PrimitiveMapper); export { PrimitiveMapper };