I have a custom validator constraint and annotation created for checking whether entity with given property already exists or not, here is the code
import { Inject, Injectable } from '#nestjs/common';
import { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint } from 'class-validator';
import { ValidatorConstraintInterface } from 'class-validator/types/validation/ValidatorConstraintInterface';
import { Connection } from 'typeorm';
import { InjectConnection } from '#nestjs/typeorm';
#ValidatorConstraint({ async: true })
#Injectable()
export class EntityExistsConstraint implements ValidatorConstraintInterface {
constructor(#InjectConnection() private dbConnection: Connection) {
}
defaultMessage(validationArguments?: ValidationArguments): string {
return `${validationArguments.constraints[0].name} with ${validationArguments.property} already exists`;
}
validate(value: any, validationArguments?: ValidationArguments): Promise<boolean> | boolean {
const repoName = validationArguments.constraints[0];
const property = validationArguments.property;
const repository = this.dbConnection.getRepository(repoName);
return repository.findOne({ [property]: value }).then(result => {
return !result;
});
}
}
export function EntityExists(repoName, validationOptions?: ValidationOptions) {
return function(object: any, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
constraints: [repoName],
validator: EntityExistsConstraint,
});
};
}
Everything works fine, but I receive this response when the validation fails
{
"statusCode": 400,
"message": [
"User with email already exists"
],
"error": "Bad Request"
}
I want the error be Conflict Exception=> statusCode 409, how can I achieve this?
class-validator doesn't do anything with the http codes. It only validates and returns a list of errors or an empty array.
What you need to do is to check framework you use, I assume it's nestjs or routing-controllers.
In the case of routing-controllers you need to write own after middleware and disable default middleware (it converts validation errors to 400 bad requests).
More info is here: https://github.com/typestack/routing-controllers#error-handlers
In the case of nestjs - the same steps.
More info you can find here: https://docs.nestjs.com/exception-filters#catch-everything
Related
I want class validator to stop validation as soon as the first error is found.
I know there is a stopAtFirstError option, but that prevents further validation on property level only. I want to stop it globally:
#IsString() // Let's say this received invalid value
someStr: string
#IsInt() // I want this to be NOT executed
someNuber: number
Is this possible?
Since there is no official support for this, I implemented a hacky way to make it work. Although it doesn't stop the validation, only returns the message from initial one & ignores the rest.
ValidationErrorException
// validation-error.exception.ts
import { HttpException, HttpStatus } from "#nestjs/common";
export class ValidationErrorException extends HttpException {
data: any;
constructor(data: any) {
super('ValidationError', HttpStatus.BAD_REQUEST);
this.data = data
}
getData(){
return this.data;
}
}
Use Exception Factory to return the exception
// main.ts
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
stopAtFirstError: true,
exceptionFactory: (errors: ValidationError[]) => {
return new ValidationErrorException(errors);
},
}),
);
Validation Error Filter
// validation-error.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost } from '#nestjs/common';
import { Response } from 'express';
import { ValidationErrorException } from './validation-error.exception';
#Catch(ValidationErrorException)
export class ValidationErrorFilter implements ExceptionFilter {
catch(exception: ValidationErrorException, host: ArgumentsHost) {
const response = host.switchToHttp().getResponse<Response>();
const status = exception.getStatus();
let constraints = exception.getData()[0].constraints
response
.status(status)
.json({
statusCode: status,
message: constraints[Object.keys(constraints)[0]],
error: exception.message
});
}
}
Use The filter
// app.module.ts
providers: [
{
provide: APP_FILTER,
useClass: ValidationErrorFilter,
},
],
I have this code to change the default message from typeorm when a value in a unique column already exists. It just creates a custom message when we get an error 23505.
if (error.code === '23505') {
// message = This COLUMN VALUE already exists.
const message = error.detail.replace(
/^Key \((.*)\)=\((.*)\) (.*)/,
'The $1 $2 already exists.',
);
throw new BadRequestException(message);
}
throw new InternalServerErrorException();
I will have to use it in other services, so I would like to abstract that code.
I think I could just create a helper and then I import and call it wherever I need it. But I don’t know if there is a better solution to use it globally with a filter or an interceptor, so I don’t have to even import and call it in different services.
Is this possible? how can that be done?
If it is not possible, what do you think the best solution would be?
Here all the service code:
#Injectable()
export class MerchantsService {
constructor(
#InjectRepository(Merchant)
private merchantRepository: Repository<Merchant>,
) {}
public async create(createMerchantDto: CreateMerchantDto) {
try {
const user = this.merchantRepository.create({
...createMerchantDto,
documentType: DocumentType.NIT,
isActive: false,
});
await this.merchantRepository.save(user);
const { password, ...merchantData } = createMerchantDto;
return {
...merchantData,
};
} catch (error) {
if (error.code === '23505') {
// message = This COLUMN VALUE already exists.
const message = error.detail.replace(
/^Key \((.*)\)=\((.*)\) (.*)/,
'The $1 $2 already exists.',
);
throw new BadRequestException(message);
}
throw new InternalServerErrorException();
}
}
public async findOneByEmail(email: string): Promise<Merchant | null> {
return this.merchantRepository.findOneBy({ email });
}
}
I created an exception filter for typeORM errors.
This was the result:
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpStatus,
InternalServerErrorException,
} from '#nestjs/common';
import { Response } from 'express';
import { QueryFailedError, TypeORMError } from 'typeorm';
type ExceptionResponse = {
statusCode: number;
message: string;
};
#Catch(TypeORMError, QueryFailedError)
export class TypeORMExceptionFilter implements ExceptionFilter {
private defaultExceptionResponse: ExceptionResponse =
new InternalServerErrorException().getResponse() as ExceptionResponse;
private exceptionResponse: ExceptionResponse = this.defaultExceptionResponse;
catch(exception: TypeORMError | QueryFailedError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
exception instanceof QueryFailedError &&
this.setQueryFailedErrorResponse(exception);
response
.status(this.exceptionResponse.statusCode)
.json(this.exceptionResponse);
}
private setQueryFailedErrorResponse(exception: QueryFailedError): void {
const error = exception.driverError;
if (error.code === '23505') {
const message = error.detail.replace(
/^Key \((.*)\)=\((.*)\) (.*)/,
'The $1 $2 already exists.',
);
this.exceptionResponse = {
statusCode: HttpStatus.BAD_REQUEST,
message,
};
}
// Other error codes can be handled here
}
// Add more methods here to set a different response for any other typeORM error, if needed.
// All typeORM erros: https://github.com/typeorm/typeorm/tree/master/src/error
}
I set it globally:
import { TypeORMExceptionFilter } from './common';
async function bootstrap() {
//...Other code
app.useGlobalFilters(new TypeORMExceptionFilter());
//...Other code
await app.listen(3000);
}
bootstrap();
And now I don't have to add any code when doing changes in the database:
#Injectable()
export class MerchantsService {
constructor(
#InjectRepository(Merchant)
private merchantRepository: Repository<Merchant>,
) {}
public async create(createMerchantDto: CreateMerchantDto) {
const user = this.merchantRepository.create({
...createMerchantDto,
documentType: DocumentType.NIT,
isActive: false,
});
await this.merchantRepository.save(user);
const { password, ...merchantData } = createMerchantDto;
return {
...merchantData,
};
}
}
Notice that now I don't use try catch because nest is handling the exceptions. When the repository save() method returns an error (actually it is a rejected promise), it is caught in the filter.
So I use the ValidationPipe to validate my DTOs in NestJS, like this:
// auth.dto.ts
export class AuthDto {
#IsEmail()
#IsNotEmpty()
email: string;
}
Without the Exception filter the error message works as intended. I leave the email field empty and I receive an array of error messages:
// Response - Message array, but no wrapper
{
"statusCode": 400,
"message": [
"email should not be empty",
"email must be an email"
],
"error": "Bad Request"
}
Perfect. Now I want to implement a wrapper for the error messages, so I create a new filter and add it to to bootstrap:
// main.ts
async function bootstrap() {
// ...
app.useGlobalFilters(new GlobalExceptionFilter());
}
bootstrap();
// global-exception.filter.ts
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
} from '#nestjs/common';
import { Response } from 'express';
import { IncomingMessage } from 'http';
export const getStatusCode = <T>(exception: T): number => {
return exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
};
export const getErrorMessage = <T>(exception: T): string => {
return exception instanceof HttpException
? exception.message
: String(exception);
};
#Catch()
export class GlobalExceptionFilter<T> implements ExceptionFilter {
catch(exception: T, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<IncomingMessage>();
const statusCode = getStatusCode<T>(exception);
const message = getErrorMessage<T>(exception);
response.status(statusCode).json({
error: {
timestamp: new Date().toISOString(),
path: request.url,
statusCode,
message,
},
});
}
}
It works great for most of my errors:
// Response - Good format (wrapped), single message expected
{
"error": {
"timestamp": "2022-05-11T19:54:59.093Z",
"path": "/auth/signup",
"statusCode": 400,
"message": "Email already in use"
}
}
But when I get a ValidationError from the ValidationPipe it should give me an array or messages like before, but it gives this message instead:
// Response - Wrapper: check, single message instead of array
{
"error": {
"timestamp": "2022-05-11T19:59:17.282Z",
"path": "/auth/signup",
"statusCode": 400,
"message": "Bad Request Exception" // it should be "message": ["not empty", "must be email"]
}
}
The exception object in my exception filter has a response field which contains the message array:
// HttpException object inside the filter class
{
response: {
statusCode: 400,
message: [ 'email should not be empty', 'email must be an email' ],
error: 'Bad Request'
},
status: 400
}
But exception.response.message doesn't work, because the field is private and TypeScript throws an error:Property 'response' is private and only accessible within class 'HttpException'.
Does any of you know how could I reach the message array, so I could format my error response properly?
EDIT: Sorry for the long post!
As #tobias-s commented, there's a workaround, which solved the problem:
Try exception["response"]["message"]. This bypasses the private restriction
As you are using #Catch decorator, you could get a HttpException or not, so we need to evaluate it.
Let's create an interface to "parse" Nest.js built-in HttpException class response:
export interface HttpExceptionResponse {
statusCode: number;
message: any;
error: string;
}
Now we can process it:
export const getErrorMessage = <T>(exception: T): any => {
if(exception instanceof HttpException) {
const errorResponse = exception.getResponse();
const errorMessage = (errorResponse as HttpExceptionResponse).message || exception.message;
return errorMessage;
} else {
return String(exception);
}
};
exception.getResponse() can be a string or an object, that's because we handle it as message: any of course.
I'm creating an Angular application connected to a Nodejs backend server. The Nodejs server response can be an array or Json object. I have to catch the correct data type according to the server response.
This is my Angular service code.
Note that my HttpClient functions return Json objects. Is there any function that returns any type of data?
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { map } from 'rxjs/operators'
import { City } from '../models/City';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class CityService {
constructor(private http: HttpClient) { }
API_URI = 'http://localhost:5000'
getCities() {
return this.http.get(`${this.API_URI}/City`);
}
getCity(id: string) {
return this.http.get(`${this.API_URI}/City/${id}`);
}
deleteCity(id: string) {
return this.http.delete(`${this.API_URI}/City/${id}`);
}
saveCity(city: City) {
return this.http.post(`${this.API_URI}/City`, city);
}
updateCity(id: string|number|undefined, updatedCity: City): Observable<City> {
return this.http.put(`${this.API_URI}/City/${id}`, updatedCity);
}
}
Thanks a lot !
Check the returned type and transform the response in a map operator, you can then handle it accordingly in your subscribe
getCities() {
return this.http.get(`${this.API_URI}/City`).pipe(
map( body => {
return {
isArray: Array.isArray(body),
data: body
}
})
)
}
It's strange behavior for an API to return either an array or object (usually it's always one or the other). I suspect there may be something missing in your understanding/processing of the response, but I could be wrong😊
The code I am trying to test the driver / repository for my nodeJS project:
import { Injectable, OnModuleInit } from '#nestjs/common';
import { mapping, types } from 'cassandra-driver';
import { Products } from './poducts.model';
import { CassandraService } from '../database/cassandra/cassandra.service';
import Uuid = types.Uuid;
#Injectable()
export class ProductsRepository implements OnModuleInit {
constructor(private cassandraService: CassandraService) {}
productsMapper: mapping.ModelMapper<Products>;
onModuleInit() {
const mappingOptions: mapping.MappingOptions = {
models: {
Products: {
tables: ['products'],
mappings: new mapping.UnderscoreCqlToCamelCaseMappings(),
},
},
};
this.productsMapper = this.cassandraService
.createMapper(mappingOptions)
.forModel('Products');
}
async getProducts() {
return (await this.productsMapper.findAll()).toArray(); // <-----Breaks here with findAll()
}
}
I am trying to write something like this:
describe('product repository get all', () => {
it('calls the repository get all', async () => {
const await productsRepository.getProducts();
expect().DoSomething()
});
});
This is the error I am getting:
Cannot read property 'findAll' of undefined
How would I accomplish a meaning-full test with Jest to get proper code coverage?
When I try to use jest to spy on the this.products.Mapper.findAll() it seems to break every time.