36 lines
890 B
TypeScript
36 lines
890 B
TypeScript
|
import { validate, validateSync as _validateSync } from 'class-validator';
|
||
|
|
||
|
export function validateSync<T extends object>(data: T): void {
|
||
|
const errors = _validateSync(data);
|
||
|
if (errors.length > 0) {
|
||
|
console.error('Validation failed, errors: ', errors);
|
||
|
throw new Error('Validation failed');
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export async function validateAsync<T extends object>(data: T): Promise<void> {
|
||
|
const errors = await validate(data);
|
||
|
if (errors.length > 0) {
|
||
|
console.error('Validation failed, errors: ', errors);
|
||
|
throw new Error('Validation failed');
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export async function validateAsyncInline<T extends object>(
|
||
|
data: T
|
||
|
): Promise<T> {
|
||
|
await validateAsync(data);
|
||
|
return data;
|
||
|
}
|
||
|
|
||
|
export function ValidateConstructor<T extends { new (...args: any[]): any }>(
|
||
|
constr: T
|
||
|
) {
|
||
|
return class extends constr {
|
||
|
constructor(...args: any[]) {
|
||
|
super(...args);
|
||
|
validateSync(this);
|
||
|
}
|
||
|
};
|
||
|
}
|