kirtan403
kirtan403

Reputation: 7421

How to define helper functions and constants in nest.js?

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:

enter image description here

// 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?

  1. In the same class as the AppConfigService with static readonly DEFAULT_PAGE_SIZE = 10
  2. Create a new service AppConstantsService which provide the public variables and inject the service in the constructors where we need to use it?
  3. 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:

  1. Creating the helpers.ts file exporting static functions : export const getDate = () => logger.log('Hi')

  2. 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

Answers (1)

Juan Rambal
Juan Rambal

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

Related Questions