UNPKG

5.75 kBMarkdownView Raw
1# NestJS Config
2
3Configuration component for NestJs.
4
5
6[![Build Status](https://travis-ci.org/nestjs-community/nestjs-config.svg?branch=master)](https://travis-ci.org/nestjs-community/nestjs-config)
7[![GitHub version](https://img.shields.io/npm/v/nestjs-config.svg)](https://www.npmjs.com/package/nestjs-config)
8[![GitHub license](https://img.shields.io/github/license/nestjs-community/nestjs-config.svg)](https://github.com/nestjs-community/nestjs-config/blob/master/LICENSE)
9[![Coverage Status](https://coveralls.io/repos/github/nestjs-community/nestjs-config/badge.svg?branch=master)](https://coveralls.io/github/nestjs-community/nestjs-config?branch=master)
10
11## Features
12
13- Load your configurations with globs
14- Support for different environment configuration, thanks to [dotenv](https://github.com/motdotla/dotenv)
15- Change and Load configuration at runtime
16
17### Installation
18
19**Yarn**
20```bash
21yarn add nestjs-config
22```
23
24**NPM**
25```bash
26npm install nestjs-config --save
27```
28
29### Getting Started
30
31Let's imagine that we have a folder called `config` in our project under `src`
32
33```bash
34
35/src
36├── app.module.ts
37├── config
38│   ├── express.ts
39│   ├── graphql.ts
40│   └── grpc.ts
41```
42
43Let's register the config module in `app.module.ts`
44
45```ts
46import * as path from 'path';
47import { Module } from '@nestjs/common';
48import { ConfigModule } from "nestjs-config";
49
50@Module({
51 imports: [
52 ConfigModule.load(),
53 ],
54})
55export class AppModule {
56
57}
58```
59That's it!
60
61Now let's say that your application isn't in a folder called `src`, it's in `./app`.
62
63```ts
64import * as path from 'path';
65import { Module } from '@nestjs/common';
66import { ConfigModule } from "nestjs-config";
67
68@Module({
69 imports: [
70 ConfigModule.load(
71 path.resolve(__dirname, 'config/**/*.{ts,js}')
72 ),
73 ],
74})
75export class AppModule {
76
77}
78```
79
80We provide as first argument the glob of our interested configuration that we want to load.
81
82### Environment configuration
83
84This package ship with the amazing [dotenv](https://github.com/motdotla/dotenv) so that you can create
85a `.env` file in your preferred location.
86
87let's create one!
88
89```bash
90# .env
91
92EXPRESS_PORT=3000
93```
94
95now in our `src/config/epxress.ts` file we can refer to that environment variable
96
97```ts
98// src/config/express.ts
99
100
101export default {
102
103 port: process.env.EXPRESS_PORT
104}
105```
106
107**Note:** By default the package look for a `.env` file in the path that you started your server from.
108If you want to specify a path for your `.env` file use the second parameter of `ConfigModule.load`.
109
110
111### Usage
112
113Now we are ready to inject our `ConfigService` everywhere we'd like.
114
115```ts
116import {ConfigService} from 'nestjs-config'
117
118
119@Injectable()
120class SomeService {
121
122 constructor(private readonly config: ConfigService) {
123 this.config = config;
124 }
125
126 isProduction() {
127
128 const env = this.config.get('app.environment');
129
130 return env === 'production';
131 }
132}
133```
134
135You can also use the `@InjectConfig` decorator instead, as following:
136
137```ts
138import {InjectConfig} from 'nestjs-config';
139
140
141@Injectable()
142class SomeService {
143
144 constructor(@InjectConfig() private readonly config) {
145 this.config = config;
146 }
147}
148```
149
150### Customer Helpers
151This feature allows you to create small helper function that computes values from configurations.
152
153example `isProduction` helper:
154
155```ts
156// src/config/express.ts
157
158
159export default {
160
161 environment: process.env.EXPRESS_PORT
162 port: process.env.EXPRESS_PORT,
163
164 // helpers
165 isProduction() {
166 return this.get('express.environment') === 'production';
167 }
168}
169```
170
171usage:
172
173```ts
174this.config.get('express').isProduction();
175
176// or
177
178this.config._isProduction(); // note the underscore prefix.
179```
180
181**Global Helpers**
182
183You can also attach helpers to the global instance as follow:
184
185```ts
186
187this.config.registerHelper('isProduction', () => {
188 return this.get('express.environment') === 'production';
189});
190```
191
192Then use it:
193
194```ts
195this.config.isProduction();
196```
197
198### ConfigService API
199
200#### get(param: string | string[], value: any = undefined): any
201Get a configuration value via path, you can use `dot notation` to traverse nested object.
202
203```ts
204this.config.get('server.port'); // 3000
205```
206
207#### set(param: string | string[], value: any = null): Config
208Set a value at runtime, it creates one if doesn't exists.
209
210```ts
211this.config.set('server.port', 2000); // {server:{ port: 2000 }}
212```
213
214#### has(param: string | string[]): boolean
215Determine if the given path for a configuration exists and set
216
217```ts
218this.config.has('server.port'); // true or false
219```
220
221#### merge(glob: string, options?: DotenvOptions): Promise<void>
222You can load other configuration at runtime. Great for package development.
223
224```ts
225@Module({})
226export class PackageModule implements NestModule {
227
228 constructor(@InjectConfig() private readonly config) {}
229
230 async configure(consumer: MiddlewareConsumer) {
231 await this.config.merge(path.join(__dirname, '**/*.config.{ts,js}'));
232 }
233}
234```
235
236#### registerHelper(name: string, fn: (...args:any[]) => any): ConfigService
237Register custom global helper
238
239```ts
240this.config.registerHelper('isProduction', () => {
241 return this.get('express.environment') === 'production';
242});
243```
244
245## Decorators
246
247It's possible to use decorators instead of injecting the ConfigService
248
249```ts
250import {Injectable, Get} from '@nestjs/common';
251import {Configurable, ConfigParam} from 'nestjs-config';
252
253@Injectable()
254export default class UserController {
255
256 @Configurable()
257 @Get("/")
258 index(@ConfigParam('my.parameter', 'deafult value') parameter) {
259 return parameter;
260 }
261}
262```
263
264Built from Fenos, Shekohex and Bashleigh