A set of opinionated NestJS extensions and modules
- @nestjsx/common - A set of NestJs decorators, interfaces and configuration for application modules bootstraping.
npm run test
Config module for nestjs using dotenv :key:
License: MIT License
A set of opinionated NestJS extensions and modules
npm run test
Issue type:
nestjs-config version
1.4.0
@nestjs/common+core or other package versions
The database would connect successfully using my settings in database.ts
TypeORM tries to connect to my unix usernames database, which I'm assuming is the default behavior when TypeORM is not passed any configuration settings.
app.module.ts:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './user/user.module';
import { ConfigModule, ConfigService} from 'nestjs-config';
import * as path from 'path';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [UserModule, ConfigModule,
ConfigModule.load(path.resolve(__dirname, 'config', '**/!(*.d).{ts,js}')),
TypeOrmModule.forRootAsync({
useFactory: (config: ConfigService) => config.get('database'),
inject: [ConfigService],
})],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {
constructor(config: ConfigService) {
console.log(config.get('database'));
}
}
database.ts
export default {
type: 'postgres',
host: process.env.TYPEORM_HOST,
username: process.env.TYPEORM_USERNAME,
password: process.env.TYPEORM_PASSWORD,
name: process.env.TYPEORM_DATABASE,
port: parseInt(process.env.TYPEORM_PORT, 10),
logging: process.env.TYPEORM_LOGGING === 'true',
entities: [
__dirname + '/../**/*.entity{.ts,.js}',
],
synchronize: process.env.production !== 'true',
};
Note the console.log(config.get('database'));
, which does correctly output the configuration object.
dotenv-safe ensures that all necessary environment variables are defined after reading from .env.
Is it possible to extend ConfigModule and/or ConfigService for using dotenv-safe?
Issue type:
[ ] question
[ ] bug report
[ ] feature request
[ ] documentation issue
[x] v2
nestjs-config version
@nestjs/common+core or other package versions
Add ConfigProvider type for managing different types of provider creation methods. Example github.com/bashleigh/nestjs-config-v2-test
Issue type:
How do you make .env
dynamic changes?
Ex:
I have .env
and production.env
. How can I change this using the npm script?
npm run start
npm run start: prod
I am using the nestjs-config package but I am not able to make this change.
Thanks in advance!
add forRoot
and forFeature
static functions to make the package usable within sub modules
Add class and parameter decorators to package for easier implementation of configurable providers. Idea
@Configurable()
export default class UserController {
async index(@ConfigParam('user.name') name: string): Promise<string> {
return name;
}
}
When I have the following config:
config/app.ts
interface Config {
clientId: string
clientSecret: string
}
const config: Config = {
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
}
export default config;
After tsc
transpiling, and running (npm run start:prod
) produces:
.../src/config/app.ts:1
(function (exports, require, module, __filename, __dirname) { interface Config {
^^^^^^
SyntaxError: Unexpected identifier
at new Script (vm.js:74:7)
at createScript (vm.js:246:10)
at Object.runInThisContext (vm.js:298:10)
at Module._compile (internal/modules/cjs/loader.js:670:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Module.require (internal/modules/cjs/loader.js:650:17)
at require (internal/modules/cjs/helpers.js:20:18)
at configPaths.reduce (.../node_modules/nestjs-config/dist/module/config.service.js:211:28)
Which is interesting, as it appears that the code uses require
and maybe that causes issues?
Thanks!
Nestjs issues a warning to use Injectable instead of Component. Replace Component decorator with Injectable.
Issue type:
[ ] question
[ ] bug report
[ ] feature request
[ ] documentation issue
[x] v2
nestjs-config version
@nestjs/common+core or other package versions
Add the config class from github.com/bashleigh/nestjs-config-v2-test
When I try to inject a param in the constructor of my class using the ConfigParam
decorator on the function argument and the Configurable
decorator in the function, as suggested by the docs, TypeScript is throwing an error on the Configurable
decorator.
This is my code:
@Configurable()
public constructor(@ConfigParam('app.env') private readonly env: string) { }
And this is the error: TS1206: Decorators are not valid here
.
I managed to make it work with this:
private readonly env: string;
public constructor(private readonly config: ConfigService) {
this.env = config.get('app.env');
}
but that defeats completly the purpose of the decorators.
Am I doing something wrong?
Issue type:
[ ] question
[x] bug report
[ ] feature request
[ ] documentation issue
nestjs-config version
@nestjs/common+core or other package versions
Classes to not be scanned for all methods
Currently the bindConfigHelpers
method will 'scan' all object keys within a config file object. Which results in unwanted methods being added to the helpers object
We need to make a decision on how to keep the existing functionality and avoid this outcome. First seen here #69 #71
Add a condition to configService.get to return Config class as object when ashPattern === ''. For using with config.get('database');
Great library, but I'm having issues using the ConfigService
to configure other modules. Can you provide some example?
I have the following folder structure (as given in the getting started section of the readme)
/src
โโโ app.module.ts
โโโ config
โ โโโ app.ts
...
In my app.module.ts, I have
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule, ConfigService } from 'nestjs-config';
@Module({
imports: [ConfigModule.load()],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {
constructor(private readonly config: ConfigService) {
this.config = config;
console.log(config); // ConfigService { helpers: {} }
AppModule.host = this.config.get('app.url');
console.log( 'App URL is', this.config.get('app.url') ); // App URL is undefined
}
...
}
What could I be doing wrong?
When using classes with typeorm options, some connection will be removed because Function typeof is not Object. Remove or make a Function to Object convertor method or something like a __toObject method
https://github.com/typeorm/typeorm/blob/master/src/index.ts#L224
Issue type:
[x] question
[ ] bug report
[ ] feature request
[ ] documentation issue
nestjs-config version
@nestjs/common+core or other package versions
ConfigModule.resolveSrcPath(__dirname).load('config/**/!(*.d).{ts,js}', { path: envPath }),
console.log node_modules/nestjs-config/dist/module/config.service.js:180
WARNING: Method 'resolveSrcPath' has been deprecated. Please use 'resolveRootPath'
Is there any way else to config the root path?
So, I've recently created an interface for prototyping a file system. The code is as follows
@Injectable()
export class FileTransformer implements TransformerInterface {
constructor(private readonly storage: Storage) {}
async handle(payload: any, @ConfigParam('google-storage.bucket') bucket: string): Promise<object[]> {
const fileStream = this.storage.bucket(bucket).file(payload).createReadStream();
return await csv().fromStream(fileStream);
}
}
Unfortunately I cannot use the ConfigParam decorator because it doesn't abide by the interface which is
export interface TransformerInterface {
handle(payload: any): Promise<object|object[]> | object | object[];
}
Need to think of a better way to inject singular parameters.
Issue type:
[ ] question
[x] bug report
[ ] feature request
[ ] documentation issue
nestjs-config version
@nestjs/common+core or other package versions
npm v har-validator --json
{
"_id": "[email protected]",
"_rev": "69-619942cfbda2c0d33d6cdcb07ff0e671",
"name": "har-validator",
"description": "Extremely fast HTTP Archive (HAR) validator using JSON Schema",
"dist-tags": {
"latest": "5.1.3"
},
"versions": [
"1.0.0",
"1.0.1",
"1.0.2",
"1.1.0",
"1.1.1",
"1.1.2",
"1.1.3",
"1.2.0",
"1.3.0",
"1.3.1",
"1.4.0",
"1.5.0",
"1.5.1",
"1.6.0",
"1.6.1",
"1.7.0",
"1.7.1",
"1.8.0",
"2.0.0",
"2.0.1",
"2.0.2",
"2.0.3",
"2.0.4",
"2.0.5",
"2.0.6",
"2.1.0",
"2.1.1",
"2.1.2",
"2.1.3",
"3.0.0",
"3.1.0",
"3.2.0",
"3.3.0",
"3.3.1",
"3.4.0",
"4.0.0",
"4.0.1",
"4.0.2",
"4.0.3",
"4.0.4",
"4.1.0",
"4.1.1",
"4.1.2",
"4.2.0",
"4.2.1",
"5.0.0",
"5.0.1",
"5.0.2",
"5.0.3",
"5.1.0",
"5.1.3"
],
"maintainers": [
"ahmadnassri <[email protected]>"
],
"time": {
"modified": "2019-01-04T02:36:14.877Z",
"created": "2015-02-10T09:34:51.208Z",
"1.0.0": "2015-02-10T09:34:51.208Z",
"1.0.1": "2015-03-04T21:10:19.824Z",
"1.0.2": "2015-03-04T21:41:18.650Z",
"1.1.0": "2015-03-05T17:09:47.634Z",
"1.1.1": "2015-03-05T17:19:39.368Z",
"1.1.2": "2015-03-05T17:22:43.677Z",
"1.1.3": "2015-03-21T07:05:36.574Z",
"1.2.0": "2015-03-21T08:09:56.553Z",
"1.3.0": "2015-03-22T05:45:54.179Z",
"1.3.1": "2015-03-22T05:56:34.528Z",
"1.4.0": "2015-03-22T05:59:49.920Z",
"1.5.0": "2015-03-30T03:31:22.173Z",
"1.5.1": "2015-03-30T03:48:16.233Z",
"1.6.0": "2015-04-02T06:31:38.556Z",
"1.6.1": "2015-04-02T07:48:31.380Z",
"1.7.0": "2015-04-30T04:01:06.241Z",
"1.7.1": "2015-05-27T09:16:55.401Z",
"1.8.0": "2015-06-22T13:59:06.322Z",
"2.0.0": "2015-10-03T20:36:43.750Z",
"2.0.1": "2015-10-03T20:56:34.699Z",
"2.0.2": "2015-10-03T22:58:44.305Z",
"2.0.3": "2015-11-24T13:59:09.905Z",
"2.0.4": "2016-01-14T06:50:03.933Z",
"2.0.5": "2016-01-14T06:59:23.497Z",
"2.0.6": "2016-01-19T23:18:30.950Z",
"2.1.0": "2016-03-08T00:32:44.494Z",
"2.1.1": "2016-03-08T00:43:19.796Z",
"2.1.2": "2016-04-16T04:05:39.404Z",
"2.1.3": "2016-04-16T04:15:21.260Z",
"3.0.0": "2016-12-02T23:30:29.307Z",
"3.1.0": "2016-12-03T19:24:47.829Z",
"3.2.0": "2016-12-03T19:31:11.165Z",
"3.3.0": "2016-12-03T22:02:25.049Z",
"3.3.1": "2016-12-03T22:53:10.083Z",
"3.4.0": "2016-12-04T00:39:58.691Z",
"4.0.0": "2016-12-04T00:46:38.983Z",
"4.0.1": "2016-12-04T01:21:02.883Z",
"4.0.2": "2016-12-04T05:38:13.182Z",
"4.0.3": "2016-12-04T05:56:32.120Z",
"4.0.4": "2016-12-04T06:54:25.245Z",
"4.1.0": "2016-12-04T08:24:24.491Z",
"4.1.1": "2016-12-04T19:33:57.708Z",
"4.1.2": "2016-12-04T19:56:05.064Z",
"4.2.0": "2016-12-04T20:12:12.333Z",
"4.2.1": "2017-03-04T14:09:00.472Z",
"5.0.0": "2017-03-14T20:50:02.584Z",
"5.0.1": "2017-03-14T21:13:14.475Z",
"5.0.2": "2017-03-14T21:34:33.483Z",
"5.0.3": "2017-05-14T15:46:08.016Z",
"5.1.0": "2017-11-03T05:55:04.210Z",
"5.1.1": "2018-11-07T02:02:25.938Z",
"5.1.2": "2018-11-07T02:04:55.963Z",
"5.1.3": "2018-11-11T00:18:56.399Z"
},
"homepage": "https://github.com/ahmadnassri/node-har-validator",
"keywords": [
"har",
"cli",
"ajv",
"http",
"archive",
"validate",
"validator"
],
"repository": {
"type": "git",
"url": "git+https://github.com/ahmadnassri/node-har-validator.git"
},
"author": "Ahmad Nassri <[email protected]> (https://www.ahmadnassri.com/)",
"bugs": {
"url": "https://github.com/ahmadnassri/node-har-validator/issues"
},
"license": "MIT",
"readmeFilename": "README.md",
"users": {
"ahmadnassri": true,
"neodon1014": true,
"mojaray2k": true
},
"_cached": false,
"_contentLength": 0,
"version": "5.1.3",
"main": "lib/promise.js",
"engines": {
"node": ">=6"
},
"scripts": {
"lint:deps": "npx updated",
"lint:ec": "npx editorconfig-checker .",
"lint:js": "npx eslint .",
"lint:md": "npx remark --quiet --frail .",
"lint": "npx run-p lint:*",
"open:coverage": "opener coverage/lcov-report/index.html",
"test": "tap test --coverage-report=lcov --no-browser"
},
"devDependencies": {
"tap": "^12.0.1"
},
"dependencies": {
"ajv": "^6.5.5",
"har-schema": "^2.0.0"
},
"gitHead": "a38c0672cd3b202bd52534ee7da83b74003eb472",
"_npmVersion": "6.4.1",
"_nodeVersion": "10.12.0",
"_npmUser": "ahmadnassri <[email protected]>",
"dist": {
"integrity": "sha512-sNvOCzEQNr/qrvJgc3UG/kD4QtlHycrzwS+6mfTrrSq97BvaYcPZZI1ZSqGSPR73Cxn4LKTD4PttRwfU7jWq5g==",
"shasum": "1ef89ebd3e4996557675eed9893110dc350fa080",
"tarball": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.3.tgz",
"fileCount": 6,
"unpackedSize": 8226,
"npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb53VxCRA9TVsSAnZWagAAxgcP/1BGWYGIW64yLNAW/WHN\nOSYoh6XrgKCrO61n8lQn2QwRNDkMVSynpPqBsdARLMT/jWh4H7Dobgfr1sjH\nmcw8zl+qVYIktLBmJh0wZ8NywAyev+Uo2ykRFNEhJJpPMEDyvqOTDxzhYJzd\nDeUjV5TllJ5KACWkpL+vTl5i9wIO1NvUAa0CGTBMRS0FiZTZDYqFAsi9Elnu\nOIPpk0J1DUUWN3ZM2OB/T6R0Oz12GdYXWU84rqb8TgJFlM0LQiKSZ2pnpVc+\nNH5hajBY8tITbel8S4FS3CrUGUzCBUIN2+bRddLiRSaLRQqYXW1tEvWU+IXS\nTv5VTChKnpPIzIclJPhrxpv7CdlCVNXjnFLrLrVeFprJXsDmU4gfwIdqD6bO\neSOnUrh9HVJqYgqMhhSOmoZHZTwM7EYLfLmmo6Ai+4jFEN7gZObr1MEdrIbI\ntqhBH4IMvmXqqpplDNAFkI4HvcG/lujIeKkgFgnvPwgZssE848Uh+nx2Su9M\ngYQnci6fbaPLO+qL5FIR+2Xlzp8rNs9QPsqxukQUcake2XoQ0Est6XCzojFi\nwMuNjpltWX9prRpttiJ/k+XLO0uvYt2AGl+4U4Q7RWquospACW9XDIIsL3Af\nHUdilD8jf2cQEmfZTHJ1Qr809sdKki4xdBYgsne08DnnuBjdfiAFh8pQp1II\nlF7b\r\n=cKta\r\n-----END PGP SIGNATURE-----\r\n"
},
"directories": {},
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/har-validator_5.1.3_1541895536289_0.3289158818028399"
},
"_hasShrinkwrap": false
}
missing version 5.1.2
, install failed
I'll give a PR
Dear all,
thank you very much for this nice package. I am quite new to TypeScript - therefore, this might be a stupid question. Anyway, I am going for this ๐
Consider the following scenario (folder structure):
src
app
modules
cat
config
cat-config.ts
customconfig.ts
whatever.ts
dog
config
dog-config.ts
snake
config
snake-config.ts
config
app.ts
database.ts
filesystem.ts
Basically, i would like to load all config files which are scattered around my application. Basic config files, like the app.ts
or database.ts
are stored in the src/app/config
folder, whereas "domain specific" config files are located within their own module folder (e.g., the cat
module has its configuration stored in src/app/modules/cat/config/cat-config.ts
Upon start of the application, i would like to get and merge all config files together, so i can use config.get('cat-config.deeply.nested.value');
to access specific values.
How can i manage to solve this?
All the best
Issue type:
[ ] question
[ ] bug report
[ ] feature request
[ ] documentation issue
[x] v2
nestjs-config version
@nestjs/common+core or other package versions
Add the v2 dynamic providers from github.com/bashleigh/nestjs-config-v2-test
Create a changelog plez
Issue type:
nestjs-config version
@nestjs/common+core or other package versions
I must be missing something but using your approach you are mostly losing the benefit of types in typescript.
Wouldn't be possible to provide config tools without a get function in the middle and by accessing typed config properties directly?
Issue type:
nestjs-config version
1.4.1
@nestjs/common+core or other package versions
When nestjs-config is added to another project which has the strict
flag enabled in its tsconfig.json
file, the project fails to build.
The project which depends on nestjs-config
should be built with strict
flag enabled in tsconfig.json
.
strict
flag to true
on a project which depends on nestjs-config
.tsc
.> tsc
node_modules/nestjs-config/dist/module/config.service.d.ts:1:37 - error TS7016: Could not find a declaration file for module 'dotenv'. '/Users/b/crew/nestjs-demo/terminus-test/node_modules/nestjs-config/node_modules/dotenv/lib/main.js' implicitly has an 'any' type.
Try `npm install @types/dotenv` if it exists or add a new declaration (.d.ts) file containing `declare module 'dotenv';`
1 import { DotenvConfigOptions } from 'dotenv';
~~~~~~~~
because typeof null === 'object'
Consider adding a merge to the array https://github.com/nestjs-community/nestjs-config/blob/master/src/module/config.service.ts#L268
Or consider immutability
In https://docs.nestjs.com/techniques/configuration it suggests to use joi.
Issue type:
nestjs-config version
1.3.21
@nestjs/common+core or other package versions
6.1.0
6.1.0
Library worked great for me on a different project. I want to use this library with a new project, but this time I am trying to use the Webpack HMR capabilities to make the app reload a lot faster. Since Nest ships with this out-of-the-box would it be nice to have some kind of recipe for supporting this flow?
I'm not familiar with the internals of this library so not sure if it's even possible to be honest. It would be really handy to be able to use this library with HMR though!
ConfigModule.resolveRootPath(__dirname).load('config/**/!(*.d).{ts,js}')
Works using yarn start
with ts-node
. Doesn't work with yarn start:hmr
. The module initializes but no configuration is being read. Likely because all of the configuration is being appended into the server.js
and is no longer in a config
folder.
Issue type:
[ ] question
[ ] bug report
[ ] feature request
[ ] documentation issue
[x] v2
nestjs-config version
@nestjs/common+core or other package versions
Add a class with helpful methods to be created when instancing the module
we need one or more tests to check for fallback value, as i think i forget to implement it
i think we just need to edit
https://github.com/nestjs-community/nestjs-config/blob/45fecdf92df151f70cb5311bf40bee04ac7a20cc/src/utils.ts#L15-L18
at line 17
to
const fallback = param.fallback;
args[param.parameterIndex] = fn(param.configKey) || fallback;
Injecting the whole ConfigService
seems a bit overkill if only one parameter is needed (and also not a good practice).
Would it be possible to create a decorator to inject only one parameter? Something like @InjectConfigParam('port')
Issue type:
[ ] question
[ ] bug report
[ ] feature request
[ ] documentation issue
[x] v2
nestjs-config version
@nestjs/common+core or other package versions
Create the forRoot and ForAsync methods in www.github.com/bashleigh/nestjs-config-v2-test
Issue type:
[ ] question
[x] bug report
[ ] feature request
[ ] documentation issue
nestjs-config version
1.2.9
@nestjs/common+core or other package versions
Not throwing an exception
I am using nest-config
with nest-winston
, but it seems that new transports.Console()
is crashing the ConfigService.
winston.options.ts
import { TransformableInfo } from 'logform'
import { format, LoggerOptions, transports } from 'winston'
const printFormat = (info: TransformableInfo) => {
return `${info.timestamp} ${info.level}: ${info.message}`
}
const options: LoggerOptions = {
transports: [
new transports.Console()
]
}
export default options
custom LoggerModule.ts
import { WinstonModule } from 'nest-winston'
import { ConfigService } from 'nestjs-config'
export const LoggerModule = WinstonModule.forRootAsync(
{
useFactory: (configService: ConfigService) => {
const options = configService.get('winston.options')
console.log(options)
return options
},
inject: [ConfigService]
}
)
[ExceptionHandler] Cannot convert undefined or null to object
TypeError: Cannot convert undefined or null to object
at Function.keys (<anonymous>)
at Object.bindCustomHelpers (/usr/src/app/node_modules/nestjs-config/dist/module/config.service.js:226:23)
at Object.keys.reduce (/usr/src/app/node_modules/nestjs-config/dist/module/config.service.js:233:46)
at Array.reduce (<anonymous>)
at Object.bindCustomHelpers (/usr/src/app/node_modules/nestjs-config/dist/module/config.service.js:226:36)
at Object.keys.reduce (/usr/src/app/node_modules/nestjs-config/dist/module/config.service.js:233:46)
at Array.reduce (<anonymous>)
at Object.bindCustomHelpers (/usr/src/app/node_modules/nestjs-config/dist/module/config.service.js:226:36)
at Object.keys.reduce (/usr/src/app/node_modules/nestjs-config/dist/module/config.service.js:233:46)
at Array.reduce (<anonymous>)
at Object.bindCustomHelpers (/usr/src/app/node_modules/nestjs-config/dist/module/config.service.js:226:36)
at Object.keys.reduce (/usr/src/app/node_modules/nestjs-config/dist/module/config.service.js:233:46)
at Array.reduce (<anonymous>)
at Object.bindCustomHelpers (/usr/src/app/node_modules/nestjs-config/dist/module/config.service.js:226:36)
at Object.keys.reduce (/usr/src/app/node_modules/nestjs-config/dist/module/config.service.js:233:46)
at Array.reduce (<anonymous>)
Issue type:
[ ] question
[ ] bug report
[ ] feature request
[ ] documentation issue
[x] v2
nestjs-config version
@nestjs/common+core or other package versions
Update all associated packages to github.com/bashleigh/nestjs-config-v2-test
Issue type:
[ ] question
[x] bug report
[ ] feature request
[ ] documentation issue
nestjs-config version
@latest
@nestjs/common+core or other package versions
No warnings
WARNING!!
The "modules" key in the @Module() decorator is deprecated and will be removed within next major release. Use the "imports" key instead.
I've been debating for a while if the method of storing application configurations in an injectable class is the best approach. Since the AsyncProvider was added to nestjs it would be possible to await the loading of the config module to create providers for each file found from the glob.
This method would make the config providers easier to import into the constructors of injectables and would clear up implementation issues and the need for injecting the entire configuration class #30, #12.
However it does mean that some functionality could be lost. Specifically the ConfigService would be rendered redundant unless we're able to inject all config providers as one provider into the ConfigService class.
If you like the idea give this comment a โค๏ธ. If you don't, add a ๐.
Remove ConfigService injection and instead create a provider for each config file
class ConfigModule {
public static async asyncLoad(glob: string, options: ConfigOptions): Promise<DynamicModule> {
const configs = await ConfigService.findByGlob(glob);
configs.map(config => ({
provide: configToken(config.fileName),
useValue: config.value,
}));
return {
module: ConfigModule,
providers: configs,
exports: configs,
};
}
}
@Controller()
export class ExampleController {
constructor(@InjectConfig('filename') config) {}
}
@Injectable()
export class ExampleProvider {
constructor(@InjectConfig('database') database, @InjectConfig('another') Another) {}
}
@Module({
imports: [
TypeOrmModule.forRootAsync((
useFactory: (config) => config,
inject: [configToken('database')],
}),
],
})
Using types in the config could be very beneficial for validation and obviously typing in the project.
configs/app.config.ts
export default class AppConfig {
port: number = process.env.PORT;
development: boolean = process.env.NODE_ENV === 'development';
}
@Module({
imports: [
SomeModule.forRootAsync({
useFactory: (config: AppConfig) => config,
injects: [AppConfig],
}),
],
})
or
@Injectable()
export class SomeClass {
constructor(private readonly myConfig: AppConfig) {}
}
export default {
'__provide': 'SOME_TOKEN',
'__name': 'name_of_config',
port: process.env.PORT,
}
This could then be injected with
@Module({
providers: [
{
provide: SomeProvider,
useFactory: (config) => config,
inject: ['SOME_TOKEN'],
},
],
})
@Injectable()
export class SomeClass {
constructor(@Inject('SOME_TOKEN') private readonly config) {}
}
Or selected with ConfigService.get('name_of_config.port')
.
Hello,
as written in docs:
Note: By default the package look for a .env file in the path that you have started your server from. If you want to specify another path for your .env file, use the second parameter of ConfigModule.load().
I'd like to set different .env file for Test module.
When i'm doing
ConfigModule.load(
path.resolve(__dirname, 'config/*.{ts,js}'),
{
path: 'mypath/.env.test',
}
)
I'm getting
error TS2345: Argument of type '{ path: string; }' is not assignable to parameter of type 'ConfigOptions'.
So, how should options
parameter looks like?
Also is there a possibility, to extend in .env.test
file values from default .env
file, so wouldn't i have to duplicate code?
Thanks
I want to set app port using nestjs-config, how to use it in main.ts
?
Error:(1, 10) TS2305: Module '"@types/dotenv"' has no exported member 'DotenvOptions'.
The static method ConfigService::src doesn't resolve src but instead resolves cwd.
The loadConfigAsync method should be refactored to use the static root method instead of the src method and possibly add a condition to determine whether to use src or root+dist based on NODE_ENV
. Or even just use the directory of the relevant call from the module?
Issue type:
[ ] question
[ ] bug report
[ ] feature request
[ ] documentation issue
[x] v2
nestjs-config version
@nestjs/common+core or other package versions
Refactor the config service as of http://github.com/bashleigh/nestjs-config-v2-test
Dear all,
thanks for this wonderful package.
I recently stumbled upon an issue where i would like to get your input on how to deal with this properly (e.g., best practice).
Consider the following config file:
// config/debug.ts
export default {
debug_mode: process.env.APP_DEBUG || false,
};
Basically, it reads the .env
file to get the APP_DEBUG
config value, otherwise it is set to false
.
Now, if i want to use it like this in a service:
if (configService.get('debug.debug_mode', false) === true) {
// do something that needs to be done, if the debug mode is enabled, e.g., extensive logging
}
this is never executed, because the value, that is read from the .env
file is interpreted as string
(e.g., typeof configService.get('debug.debug_mode')
is string
and not boolean
as one would guess.
How do you deal with boolean values in .env
files specifically?
For now, the best approach for me is as follows
// "cast" it as boolean
const enabled = !! configService.get('debug.debug_mode', false);
if (enabled === true) { /* ... */ }
What would you suggest?
All the best
Add the new method option for modifyConfigName to the README.
Also add an example of multi-modular config setups in the examples dir
related to conversation on #42
add the ability to add custom functions into the ts config files
Issue type:
nestjs-config version
@latest + @next
@nestjs/common+core or other package versions
Axios needs updating to v0.19.0 once nestjs/nest#2311 has been released
It would be a better idea to set @nestjs/common
as a peer dependancy instead of a dependancy
Hey there!
I was trying for the first time your very good looking library but I could not get it working on my setup.
I digged a bit to find out what's the problem and it seems that the last 'node-glob' version is breaking some things on Windows.
When resolving configuration files, it transforms the backslashes into forward slashes, look at this code : https://github.com/isaacs/node-glob/blob/master/common.js#L104
So Nest-config get some path like 'C:/Users/Me/project/production', and uses the path.sep
method to split it (here). But, on Windows, the path.sep
obviously resolves with a backslash '\', so it doesn't split anything here.
Then we have bad configuration names with the full file path instead of the file name, so everything gets 'undefined' when trying to get some values!
I don't know if it's a glob issue or a Nest-config one. I could prepare a workaround if needed :)
Let me know!
Issue type:
nestjs-config version
1.3.21
@nestjs/common+core or other package versions
6.1.1
6.1.1
It should be possible to pass arguments to dotenv in order to configure it.
For example, it should be possible to change the .env files path.
It is not possible to pass arguments to dotenv because only modifyConfigName key is allowed in ConfigOptions interface.
It works properly with typescript 3.3.4000 but not with 3.4.1
It seems that ConfigOptions does not extends DotenvConfigOptions the same way with those two versions of typescript.
const config = process.env.CONFIG || ''; // allow us to provide configuration easily for local environment and CI environment
return ConfigModule.load(path.resolve(__dirname, 'config', '**/!(*.d).{ts,js}'), {path: path.resolve(__dirname, `config/env/${config}.env`)});
Error
src/app.module.ts:34:85 - error TS2345: Argument of type '{ path: string; }' is not assignable to parameter of type 'ConfigOptions'.
Object literal may only specify known properties, and 'path' does not exist in type 'ConfigOptions'.
34 return ConfigModule.load(path.resolve(__dirname, 'config', '**/!(*.d).{ts,js}'), {path: path.resolve(__dirname, `config/env/${config}.env`)});
Changing nestjs dependencies release does not affect the behavior :
nestjs | typescript | nestjs-config | status |
---|---|---|---|
6.1.x | 3.3.4000 | 1.3.21 | works |
6.0.x | 3.3.4000 | 1.3.21 | works |
6.1.x | 3.4.1 or later | 1.3.21 | fails |
6.0.x | 3.4.1 or later | 1.3.21 | fails |
I think maybe there is a logic error in the way @Configurable()
works here: apply
changes the value of this
, so your are not able to call any method or property inside a decorated method1
:
@Injectable()
class TestService {
@Configurable()
method1(@ConfigParam('foo') foo: string) {
this.method2();
}
method2() {
console.log('method2');
}
}
TypeError: this.method2 is not a function
I may be wrong; I'm not a guru in JavaScript but I fear we can't solve this. At least, this should be clearly explained in the documentation.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.