fileserver/dto/utils.ts

42 lines
953 B
TypeScript

import { validate, validateSync as _validateSync } from 'class-validator';
export enum UserRole {
ADMIN = 2,
USER = 1,
DISABLED = 0
}
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);
}
};
}