Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
public static async createUser(ctx: BaseContext) {
// get a user repository to perform operations with user
const userRepository: Repository = getManager().getRepository(User);
// build up entity user to be saved
const userToBeSaved: User = new User();
userToBeSaved.name = ctx.request.body.name;
userToBeSaved.email = ctx.request.body.email;
// validate user entity
const errors: ValidationError[] = await validate(userToBeSaved); // errors is an array of validation errors
if (errors.length > 0) {
// return BAD REQUEST status code and errors array
ctx.status = 400;
ctx.body = errors;
} else if (await userRepository.findOne({ email: userToBeSaved.email })) {
// return BAD REQUEST status code and email already exists error
ctx.status = 400;
ctx.body = 'The specified e-mail address already exists';
} else {
// save the user contained in the POST body
const user = await userRepository.save(userToBeSaved);
// return CREATED status code and updated user
ctx.status = 201;
ctx.body = user;
}
private async plainToClass(dto: TDto, obj: any): Promise {
if (!obj) {
return undefined;
}
const result = plainToClassFromExist(dto, obj);
const errors = await validate(result, {
whitelist: true,
});
if (errors.length > 0) {
throw new BadRequestException(errors);
}
const repository = getRepository(this.entity);
await Promise.all(
repository.metadata.columns.map(async (column: ColumnMetadata) => {
const propType = GetPropertyType(repository.metadata.columns, column.propertyName);
if (
result[column.propertyName] &&
propType === 'uuid' &&
const validateRequest = async (
Validator: any,
payload: IPayload,
action?: string,
): Promise => {
let resource = new Validator(payload);
let validationErrors = {};
Object.entries(payload).forEach(([key, value]) => {
resource[key] =
typeof value === 'string' ? value.replace(/ +/g, '').trim() : value;
});
const errors = await validate(resource, {
validationError: { target: false },
skipMissingProperties: action === 'update' ? true : false,
});
if (errors.length === 0) {
return false;
}
for (let error of errors) {
validationErrors = {
...validationErrors,
[error.property]: Object.entries(error.constraints).map(
([, value]) => value,
),
};
}
router.post('/', async (req: Request, res: Response) => {
let user: User = await User.findOne({ email: req.body.email });
if (user) {
return res.status(400).send('Email already in use');
}
user = new User(req.body);
const errors = await validate(user);
if (!_.isEmpty(errors)) {
return res.status(400).send(getValidationErrors(errors));
}
user = await user.save();
res.header('x-auth-token', user.token).send(_.pick(user, ['id', 'email']));
});
async transform(value: any, { metatype }: ArgumentMetadata) {
const dtoOptions = this.reflector.get(DTO_META_KEY, metatype);
if (value && dtoOptions) {
const entity = plainToClass(metatype as any, value);
const errors = await validate(entity, dtoOptions);
if (errors.length > 0) {
throw new UnprocessableEntityException({
message: 'Validation Failed.',
errors: errors.map(e => this.mapErrors(e, ''))
});
}
return entity;
}
return value;
}
async transform(value, metadata: ArgumentMetadata) {
const { metatype } = metadata
if (!metatype || !this.isValidMetatype(metatype)) {
this.throwInvalidParamsException()
}
const object = plainToClass(metatype, value)
const errors = await validate(object, validatorOpts)
if (errors.length > 0) {
this.throwInvalidParamsException()
}
return value
}
async validateAsync() {
const errors = await validate(this);
this.errors = errors;
await this.validateGovernmentAsync();
}
async transform(value: any, metadata: ArgumentMetadata) {
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
throw new BadRequestException('Validation failed');
}
return value;
}
public async transform(value, metadata: ArgumentMetadata) {
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const entity = plainToClass(metatype, value);
const errors = await validate(entity, { validationError: { target: false } });
if (errors.length > 0) {
throw new BadRequestException(errors);
}
return entity;
}