UNPKG

problem-details

Version:

HTTP problem details model based on RFC7807

65 lines 2.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var problem_definition_1 = require("../models/problem-definition"); var class_validator_1 = require("class-validator"); var class_transformer_1 = require("class-transformer"); var DefinitionFactory = /** @class */ (function () { function DefinitionFactory() { /** * Stores all the registered problem details to help * aid the developer in reusing exceptions. */ this.definitionsMap = new Map(); } DefinitionFactory.prototype.isValid = function (definition) { // transfor non literal objects to class objects // (needed for validation) definition = class_transformer_1.plainToClass(problem_definition_1.ProblemDefinition, definition); // validate definition var validationErrros = class_validator_1.validateSync(definition); return validationErrros.length === 0; }; /** * Registers a definition to the internal map so developers * only need to reference the `code`, instead of throwing a * completely new problem detail object. * @param definition Definition that needs to be registered */ DefinitionFactory.prototype.register = function (definition) { if (!this.isValid(definition)) { throw new Error('malformed definition, please check documentation'); } if (this.definitionsMap.get(definition.code) !== undefined) { throw new Error('unable to register definition with allready existing code'); } // insert definition into the map this.definitionsMap.set(definition.code, definition); }; /** * Loads an array of definitions into the defintions map * @param definitions Array of defintions */ DefinitionFactory.prototype.load = function (definitions) { var _this = this; definitions.forEach(function (def) { return _this.register(def); }); }; /** * Returns a copy all registered definitions */ DefinitionFactory.prototype.getDefinitions = function () { return Array.from(this.definitionsMap.values()); }; /** * Returns a definition based on the matching code. * @param code Refrence to a registered definition */ DefinitionFactory.prototype.getByCode = function (code) { var def = this.definitionsMap.get(code); if (!def) throw new Error('unable to get definition of non existing code'); return def; }; return DefinitionFactory; }()); exports.DefinitionFactory = DefinitionFactory; //# sourceMappingURL=definition.factory.js.map