In order to not repeat your destination configuration for every request execution, you can set a destinations
environment variable to manage your destinations. In Node.js
application, it is common to use a .env
file to maintain such environment variables for a given project. Create a .env
file in the root directory of your project and define the destinations
environment variable as follows:
destinations=[{"name": "<DESTINATIONNAME>", "url": "<URL to your system>", "username": "<USERNAME>", "password": "<PASSWORD>"}]
This is what it would look like for the mock server:
destinations=[{"name": "MockServer", "url": "http://localhost:3000"}]
Now that we have defined our destinations, we need to make sure that they are available in our process. For this we use the config
package provided by nest.js
. You can install it with the following command:
npm install @nestjs/config
In order to load the environment variables defined in the .env
file, we need to add the ConfigModule
provided by the config
package to the application’s @Module
definition. Open app.module.ts
and update it with the following code:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { BusinessPartnerController } from './business-partner.controller';
@Module({
imports: [ConfigModule.forRoot()],
controllers: [AppController, BusinessPartnerController],
providers: [AppService],
})
export class AppModule {}
In line 2, ConfigModule
is imported from the config
package and in line 8 we add it to the module’s imports
. If no arguments are passed to the forRoot()
method, the .env
file has to be located in the project root. For details on the possible configuration see the nest documentation. To reference a destination in the request execution, simply replace the url
with a destinationName
- MockServer
in our example:
function getAllBusinessPartners(): Promise<BusinessPartner[]> {
return BusinessPartner.requestBuilder()
.getAll()
.execute({
destinationName: 'MockServer'
});
}
Note, that every environment variable in the .env
file has to be defined on one line. You can add more destinations to the array.