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
This commit is contained in:
committed by
GitHub
parent
7ce57c9c83
commit
adb55fa965
@@ -17,7 +17,6 @@ import {
|
||||
BelongsTo,
|
||||
Column,
|
||||
Default,
|
||||
Length,
|
||||
PrimaryKey,
|
||||
Table,
|
||||
BeforeValidate,
|
||||
@@ -51,6 +50,7 @@ import User from "./User";
|
||||
import View from "./View";
|
||||
import ParanoidModel from "./base/ParanoidModel";
|
||||
import Fix from "./decorators/Fix";
|
||||
import { Length } from "./decorators/Length";
|
||||
|
||||
export type SearchResponse = {
|
||||
results: {
|
||||
|
||||
27
server/models/decorators/Length.ts
Normal file
27
server/models/decorators/Length.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
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);
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user