@tsed/schema
Version:
JsonSchema module for Ts.ED Framework
125 lines (124 loc) • 3.43 kB
JavaScript
import { DecoratorTypes } from "@tsed/core";
import { JsonEntityStore } from "../../domain/JsonEntityStore.js";
/**
* Set the type of the item collection. The possible value is String, Boolean, Number, Date, Object, Class, etc...
*
* ```typescript
* class Model {
* @CollectionOf(String).MinLength(0).MaxLength(0)
* property: string[];
* }
* ```
* ::: warning
* You mustn't use the `type Type = string | number` as parameters Type.
*
* This example doesn't work:
*
* ```typescript
* type Type = "string" | "number"
* class Model {
* @CollectionOf(Type)
* property: Type[];
* }
* ```
* :::
*
* @param {Type<any>} type
* @param collectionType
* @decorator
* @validation
* @swagger
* @schema
* @input
* @collections
*/
export function CollectionOf(type, collectionType) {
if (!type) {
throw new Error("A type is required on `@CollectionOf(type)` decorator. Please give a type or wrap it inside an arrow function if you have a circular reference.");
}
const schema = {};
let contains = false;
const nestedGenerics = [];
const decorator = (...args) => {
const store = JsonEntityStore.from(...args);
if (collectionType) {
store.collectionType = collectionType;
store.schema.type(collectionType);
}
store.type = type;
store.itemSchema.type(type);
store.schema.assign(schema);
if (nestedGenerics.length) {
if (store.is(DecoratorTypes.PARAM)) {
store.parameter.itemSchema().genericOf(...nestedGenerics);
}
else {
store.itemSchema.genericOf(...nestedGenerics);
}
}
if (store.isArray && contains) {
store.schema.set("contains", store.schema.get("items"));
store.schema.delete("items");
}
};
/**
* @deprecated Since 2025-05-12. Use MinItems decorator instead.
*/
decorator.MinItems = (minItems) => {
schema.minItems = minItems;
return decorator;
};
/**
* @deprecated Since 2025-05-12. Use MaxItems decorator instead.
*/
decorator.MaxItems = (maxItems) => {
schema.maxItems = maxItems;
return decorator;
};
/**
* @deprecated Since 2025-05-12. Use MinProperties decorator instead.
*/
decorator.MinProperties = (minProperties) => {
schema.minProperties = minProperties;
return decorator;
};
/**
* @deprecated Since 2025-05-12. Use MaxProperties decorator instead.
*/
decorator.MaxProperties = (maxProperties) => {
schema.maxProperties = maxProperties;
return decorator;
};
decorator.Contains = () => {
contains = true;
return decorator;
};
/**
* @deprecated Since 2025-05-12. Use UniqueItems decorator instead.
*/
decorator.UniqueItems = (uniqueItems = true) => {
schema.uniqueItems = uniqueItems;
return decorator;
};
decorator.Nested = (...generics) => {
nestedGenerics.push(generics);
return decorator;
};
return decorator;
}
/**
* Alias of @@GenericOf@@ decorator.
* @param type
* @decorator
*/
export function ArrayOf(type) {
return CollectionOf(type, Array);
}
/**
* Alias of @@GenericOf@@ decorator.
* @param type
* @decorator
*/
export function MapOf(type) {
return CollectionOf(type, Map);
}