I'm learning nest.js and creating an api using it. However, I'm stuck at one of the problem, defining constants and helper functions.
As in all the APIs, I've some APIs which has the pagination and I want to define the default page size at global level for all the modules. However, at this point I'm confused what should be the way to go. For the config, I've created a AppConfigModule which provides the 4 env variables:
// app-config.service.ts
import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
@Injectable()
export class AppConfigService {
constructor(private configService: ConfigService) {}
get DB_HOST(): string {
return this.configService.get<string>('DATABASE_HOST')
}
get DB_PORT(): string {
return this.configService.get<string>('DATABASE_PORT')
}
get DB_NAME(): string {
return this.configService.get<string>('DATABASE_NAME')
}
get DB_MONGO(): string {
return `mongodb://${this.DB_HOST}:${this.DB_PORT}/${this.DB_NAME}`
}
}
Now when I've to use the constants that are not dependent on the env, for example DEFAULT_PAGE_SIZE, where should I define it?
- In the same class as the
AppConfigServicewithstatic readonly DEFAULT_PAGE_SIZE = 10 - Create a new service
AppConstantsServicewhich provide the public variables and inject the service in the constructors where we need to use it? - Create a app-constats.ts file in some helper class with below details :
export class AppConstants { static readonly DEFAULT_PAGINATION = 10 }
The same issue when I'm thinking of defining the helper functions. There are multiple ways and I'm not able to find a better clear approach for the nest js. The ways can include:
Creating the
helpers.tsfile exporting static functions :export const getDate = () => logger.log('Hi')Creating the
AppUtilServicewith the new module and inject it in the constructors whenever I need to use it?
I'm a bit confused with the approaches here for nest.js architecture. Can anyone help here?
Thanks in advance.
