Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async create(dto: CreateUserDto): Promise {
// check uniqueness of username/email
const {username, email, password} = dto;
const qb = await getRepository(UserEntity)
.createQueryBuilder('user')
.where('user.username = :username', { username })
.orWhere('user.email = :email', { email });
const user = await qb.getOne();
if (user) {
const errors = {username: 'Username and email must be unique.'};
throw new HttpException({message: 'Input data validation failed', errors}, HttpStatus.BAD_REQUEST);
}
// create new user
let newUser = new UserEntity();
newUser.username = username;
newUser.email = email;
newUser.password = password;
newUser.articles = [];
const errors = await validate(newUser);
if (errors.length > 0) {
const _errors = {username: 'Userinput is not valid.'};
throw new HttpException({message: 'Input data validation failed', _errors}, HttpStatus.BAD_REQUEST);
} else {
private handleError(error: Error & { code?: number; statusCode?: number }) {
const message = error.message || 'unknown error';
const statusCode = error.statusCode || error.code || HttpStatus.I_AM_A_TEAPOT;
console.log(message, statusCode);
switch (statusCode) {
case HttpStatus.CONFLICT:
throw new ConflictException(error.message);
case HttpStatus.UNAUTHORIZED:
throw new UnauthorizedException(error.message);
case HttpStatus.NOT_FOUND:
throw new NotFoundException(error.message);
case HttpStatus.BAD_REQUEST:
throw new BadRequestException(error.message);
default:
throw new HttpException(message, statusCode);
}
}
}
async createHero(@Body() body) {
if (!body || !body.name) {
throw new HttpException('Missing hero name', HttpStatus.BAD_REQUEST);
}
return this.heroesService.createHero(body.name);
}
async transform(value, 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 HttpException('Validation failed', HttpStatus.BAD_REQUEST);
}
return value;
}
import { User } from '../user/models';
import { getOperationId } from '../utilities/get-operation-id';
import { UserDTO, UserRole } from './models';
import { UserService } from './user.service';
@Controller('users')
@ApiUseTags('User')
@ApiBearerAuth()
export class UserController {
constructor(private readonly _userService: UserService) {}
@Put('update')
@UseGuards(AuthGuard(), RolesGuard)
@Roles(UserRole.Admin)
@ApiResponse({ status: HttpStatus.CREATED, type: UserDTO })
@ApiResponse({ status: HttpStatus.BAD_REQUEST, type: ApiException })
@ApiOperation(getOperationId('User', 'Update'))
async update(@Body() userUpdate: Partial): Promise {
try {
const exist = await this._userService.findById(userUpdate.id);
if (!exist) {
throw new HttpException(
` This request can not be processed`,
HttpStatus.NOT_FOUND,
);
}
if (userUpdate.mail && userUpdate.mail.trim() !== '') {
exist.mail = userUpdate.mail;
}
const updated = await this._userService.update(userUpdate.id, exist);
if (updated) {
constructor(errors: string | object | any) {
super(
createHttpExceptionBody(errors, 'VALIDATION_EXCEPTION', HttpStatus.BAD_REQUEST),
HttpStatus.BAD_REQUEST,
);
}
}
private response(
exception: CustomValidationError | SyntaxError | Error | HttpException,
host: ArgumentsHost,
data: any,
status?: number,
) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const request = ctx.getRequest();
Logger.error(
JSON.stringify(exception),
undefined,
CustomExceptionFilter.name,
);
response.status(status ? status : HttpStatus.BAD_REQUEST).json(data);
}
constructor(errors: string | object | any) {
super(
createHttpExceptionBody(errors, 'VALIDATION_EXCEPTION', HttpStatus.BAD_REQUEST),
HttpStatus.BAD_REQUEST,
);
}
}
constructor(message?: string) {
super(
message || 'Request format is invalid',
HttpStatus.BAD_REQUEST
);
}
}
async transform(value: any, metadata: ArgumentMetadata) {
if (value instanceof Object && this.isEmpty(value)) {
throw new HttpException(
'Validation failed: No body submitted',
HttpStatus.BAD_REQUEST,
);
}
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 HttpException(
`Validation failed: ${this.formatErrors(errors)}`,
HttpStatus.BAD_REQUEST,
);
}
return value;
}