UNPKG

ts-deserializable

Version:

Decorator pattern for deserializing unverified data to an instance of a class in typescript.

57 lines (56 loc) 2.51 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ReportType; (function (ReportType) { ReportType["Ignore"] = "Ignore"; ReportType["Warn"] = "Warning"; ReportType["Error"] = "Error"; ReportType["Throw"] = "Thrown Error"; })(ReportType = exports.ReportType || (exports.ReportType = {})); class DeserializerReporter { constructor(actionType, instanceName, errorCtor) { this.actionType = actionType; this.instanceName = instanceName; this.errorCtor = errorCtor; this.marks = []; this.invalidMarks = []; this.logPattern = (errorType, instanceName) => `Deserialization ${errorType} - issue deserializing instance of "${instanceName}":`; this.propPattern = (key, value, fallback) => `\n "${key}" was ${JSON.stringify(value)}, provided -> ${JSON.stringify(fallback)}`; this.invalidPattern = (key, value, fallback) => `\n "${key} was ${JSON.stringify(value)} and did not pass validation, provided -> ${JSON.stringify(fallback)}`; } mark(key, value, fallback) { this.marks = [...this.marks, { key: key, value: value, fallback: fallback }]; } markInvalid(key, value, fallback) { this.invalidMarks = [...this.invalidMarks, { key: key, value: value, fallback: fallback }]; } report() { let log = this.logPattern(this.actionType, this.instanceName); if (this.marks && this.marks.length > 0) { this.marks.forEach((mark) => { log += this.propPattern(mark.key, mark.value, mark.fallback); }); } if (this.invalidMarks && this.invalidMarks.length > 0) { this.invalidMarks.forEach((mark) => { log += this.invalidPattern(mark.key, mark.value, mark.fallback); }); } if ((this.marks && this.marks.length > 0) || (this.invalidMarks && this.invalidMarks.length > 0)) { switch (this.actionType) { case ReportType.Warn: console.warn(log); break; case ReportType.Error: console.error(log); break; case ReportType.Throw: throw new this.errorCtor(log); case ReportType.Ignore: default: break; } } } } exports.DeserializerReporter = DeserializerReporter;