Reputation: 7421
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?
AppConfigService
with static readonly DEFAULT_PAGE_SIZE = 10
AppConstantsService
which provide the public variables and inject the service in the constructors where we need to use it?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.ts
file exporting static functions : export const getDate = () => logger.log('Hi')
Creating the AppUtilService
with 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.
Upvotes: 11
Views: 28962
Reputation: 629
Yes, you can add the constants to the class as simple properties that will help you to keep all constants in one place, about the helpers functions I recommend you to create a utils folder and add a module per group of functions.
i.e
root / utils / dates -> dates.module.ts , dates.service.ts
In your dates.service.ts you can add every helper function related to date manipulation, remember to export the provider on the dates.module.ts
Upvotes: 6