fileserver/dto/src/utils.ts

36 lines
890 B
TypeScript
Raw Normal View History

2022-08-25 13:13:44 +00:00
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);
}
};
}