How to implement pagination in NestJS with TypeORM

You can find some nice example in this project. In short typeorm has a really nice method specific to this usecase findAndCount. async findAll(query): Promise<Paginate> { const take = query.take || 10 const skip = query.skip || 0 const keyword = query.keyword || ” const [result, total] = await this.userRepository.findAndCount( { where: { name: Like(‘%’ … Read more

Inject TypeORM repository into NestJS service for mock data testing

Let’s assume we have a very simple service that finds a user entity by id: export class UserService { constructor(@InjectRepository(UserEntity) private userRepository: Repository<UserEntity>) { } async findUser(userId: string): Promise<UserEntity> { return this.userRepository.findOne(userId); } } Then you can mock the UserRepository with the following mock factory (add more methods as needed): // @ts-ignore export const repositoryMockFactory: … Read more

Class-validator – validate array of objects

Add @Type(() => AuthParam) to your array and it should be working. Type decorator is required for nested objects(arrays). Your code becomes import { IsArray, ValidateNested, ArrayMinSize, ArrayMaxSize } from ‘class-validator’; import { AuthParam } from ‘./authParam.model’; import { Type } from ‘class-transformer’; export class SignInModel { @IsArray() @ValidateNested({ each: true }) @ArrayMinSize(2) @ArrayMaxSize(2) @Type(() … Read more

How to use nestjs Logging service

Best practice Better than accessing the Logger statically is to create an instance for your class: @Controller() export class AppController { private readonly logger = new Logger(AppController.name); @Get() async get() { this.logger.log(‘Getting stuff’); } } Why is this better? You can provide a context in the constructor like new Logger(AppController.name) so that the class name … Read more

NestJS – How to use .env variables in main app module file for database connection

From Nestjs docs here – https://docs.nestjs.com/techniques/configuration These steps worked for me with MySQL and TypeORM. Install Nestjs config module – npm i –save @nestjs/config. It relies on dotenv Create a .env file in your root folder and add your key/value pairs e.g. DATABASE_USER=myusername Open app.module.ts and import the config module import { ConfigModule } from … Read more

What is the nestjs error handling approach (business logic error vs. http error)?

Let’s assume your business logic throws an EntityNotFoundError and you want to map it to a NotFoundException. For that, you can create an Interceptor that transforms your errors: @Injectable() export class NotFoundInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { // next.handle() is an Observable of the controller’s result value return next.handle() .pipe(catchError(error => … Read more

How to use query parameters in Nest.js?

Query parameters You have to remove :params for it to work as expected: @Get(‘findByFilter’) async findByFilter(@Query() query): Promise<Article[]> { // … } Path parameters The :param syntax is for path parameters and matches any string on a path: @Get(‘products/:id’) getProduct(@Param(‘id’) id) { matches the routes localhost:3000/products/1 localhost:3000/products/2abc // … Route wildcards To match multiple endpoints … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)