Files
outline/server/models/decorators/Length.ts
CuriousCorrelation adb55fa965 feat: Custom Length decorator for UTF-8 chars len (#3709)
* feat: Custom Length decorator for UTF-8 chars len

* fix: Length decorator function return type
2022-07-01 13:21:09 -07:00

28 lines
693 B
TypeScript

import { size } from "lodash";
import { addAttributeOptions } from "sequelize-typescript";
/**
* A decorator that calculates size of the string based on lodash's size function.
* particularly useful for strings with unicode characters of variable lengths.
*/
export function Length({
msg,
min,
max,
}: {
msg?: string;
min: number;
max: number;
}): (target: any, propertyName: string) => void {
return (target: any, propertyName: string) =>
addAttributeOptions(target, propertyName, {
validate: {
validLength(value: string) {
if (size(value) > max || size(value) < min) {
throw new Error(msg);
}
},
},
});
}