UNPKG

@tsed/schema

Version:
86 lines (85 loc) 3.2 kB
import { __decorate, __metadata } from "tslib"; import { ancestorsOf, DecoratorTypes, isClass, isMethodDescriptor, Metadata, prototypeOf } from "@tsed/core"; import { JsonEntityComponent } from "../decorators/config/jsonEntityComponent.js"; import { JsonEntityStore } from "./JsonEntityStore.js"; import { JsonParameter } from "./JsonParameter.js"; let JsonParameterStore = class JsonParameterStore extends JsonEntityStore { constructor(options) { super(options); /** * Ref to JsonParameter when the decorated object is a parameter. */ this.parameter = new JsonParameter(); this.parent = JsonEntityStore.fromMethod(this.target, this.propertyKey); this.pipes = options.pipes || []; this.paramType = options.paramType || this.paramType; this.expression = options.expression || this.expression; this.dataPath = options.dataPath || this.dataPath; } /** * Return the required state. * @returns {boolean} */ get required() { return !!this.parameter.get("required"); } set required(value) { this.parameter.required(value); } get allowedRequiredValues() { return this.schema.getAllowedRequiredValues(); } get schema() { return this.parameter.schema(); } static getParams(target, propertyKey) { const params = []; const klass = ancestorsOf(target) .reverse() .find((target) => { return isMethodDescriptor(target, propertyKey) && JsonEntityStore.fromMethod(target, propertyKey).children.size; }); if (klass) { JsonEntityStore.fromMethod(klass, propertyKey).children.forEach((param, index) => { params[+index] = param; }); return params; } return []; } static get(target, propertyKey, index) { return JsonEntityStore.from(prototypeOf(target), propertyKey, index); } /** * Check precondition between value, required and allowedRequiredValues to know if the entity is required. * @param value * @returns {boolean} */ isRequired(value) { return this.required && [undefined, null, ""].includes(value) && !this.allowedRequiredValues.includes(value); } build() { if (!this._type) { const type = Metadata.getParamTypes(prototypeOf(this.target), this.propertyKey)[this.index]; this.buildType(type); } this._type = this._type || Object; this.parent.children.set(this.index, this); this.parent.operation.addParameter(this.index, this.parameter); if (this.collectionType) { this.parameter.schema().type(this.collectionType); } if (isClass(this._type)) { this.parameter.schema().itemSchema(this._type); } else { this.parameter.itemSchema().type(this._type); } } }; JsonParameterStore = __decorate([ JsonEntityComponent(DecoratorTypes.PARAM), __metadata("design:paramtypes", [Object]) ], JsonParameterStore); export { JsonParameterStore }; export const ParamMetadata = JsonParameterStore;