import { IDtoFuncArray, IDtoFuncObject, IDtoFuncBase, IDtoMeta, IDtoVerify } from "./types" function defineDtoArray(type: string, verify: IDtoVerify) { const dtoFunc = (list: any[] | any, meta: IDtoMeta) => { return { type, meta, list: Array.isArray(list) ? list : [list], __isDto__: true, } } const dtoVerify = { type, verify, } return { dtoFunc: dtoFunc as IDtoFuncArray, dtoVerify, } } function defineDtoObject(type: string, verify: IDtoVerify) { const dtoFunc = (nest: Record, meta: IDtoMeta) => { return { type, meta, nest, __isDto__: true, } } const dtoVerify = { type, verify, } return { dtoFunc: dtoFunc as IDtoFuncObject, dtoVerify, } } // ======== Array ============================================================ export const { dtoFunc: DtoArray, dtoVerify: DtoVerifyArray } = defineDtoArray<{ /** 限制数组最大长度 */ maxLength?: number /** 限制数组最小长度 */ minLength?: number }>("Array", (val, dto, meta) => { if (!Array.isArray(val)) return { isOk: false } if (meta?.maxLength !== undefined && val.length > meta?.maxLength) { return { isOk: false, msg: `array length out of range: ${val.length}>${meta?.maxLength}.` } } if (meta?.minLength !== undefined && val.length < meta?.minLength) { return { isOk: false, msg: `array length out of range: ${val.length}<${meta?.minLength}.` } } return { isOk: true } }) // ======== Object ============================================================ export const { dtoFunc: DtoObject, dtoVerify: DtoVerifyObject } = defineDtoObject<{}>("object", (val, dto, meta) => { if (typeof val !== "object" || val === null || Array.isArray(val)) return { isOk: false } return { isOk: true } })