Giter Site home page Giter Site logo

nestjs-config's Introduction

Nestjsx Logo

A set of opinionated NestJS extensions and modules

Travis Coverage Status

Packages

  • @nestjsx/common - A set of NestJs decorators, interfaces and configuration for application modules bootstraping.

Tests

npm run test

nestjs-config's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

nestjs-config's Issues

TypeORM not loading correct settings

Issue type:

  • [ x ] question
  • bug report
  • feature request
  • documentation issue

nestjs-config version

1.4.0

@nestjs/common+core or other package versions

  • @nestjs/common: 6.2.4
  • @nestjs/core: 6.2.4
  • @nestjs/typeorm: 6.1.1

Excepted behavior

The database would connect successfully using my settings in database.ts

Actual behavior or outcome (for issue):

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.

Replication/Example

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.



Add ConfigProvider type

Issue type:

[ ] question
[ ] bug report
[ ] feature request
[ ] documentation issue
[x] v2

nestjs-config version

@nestjs/common+core or other package versions

  • @nestjs/common:
  • @nestjs/core:

Add ConfigProvider type for managing different types of provider creation methods. Example github.com/bashleigh/nestjs-config-v2-test

[Question] dotenv dynamic changes for production environment

Issue type:

  • question
  • bug report
  • feature request
  • documentation issue

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!

default load

add forRoot and forFeature static functions to make the package usable within sub modules

decorators for configurable providers

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;
    }
}

Not possible to use full TypeScript syntax in the config file

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?

https://github.com/nestjs-community/nestjs-config/blob/014f8a29bb7f4b1a92911dfec0cdd667a9844b26/src/module/config.service.ts#L250

Thanks!

Nestjs update

Nestjs issues a warning to use Injectable instead of Component. Replace Component decorator with Injectable.

Add dynamic config class for creation from object files etc

Issue type:

[ ] question
[ ] bug report
[ ] feature request
[ ] documentation issue
[x] v2

nestjs-config version

@nestjs/common+core or other package versions

  • @nestjs/common: 6
  • @nestjs/core: 6

Add the config class from github.com/bashleigh/nestjs-config-v2-test

Can not inject config param in constructor

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?

bindConfigHelpers method adds unwanted methods to helpers object

Issue type:

[ ] question
[x] bug report
[ ] feature request
[ ] documentation issue

nestjs-config version

@latest

@nestjs/common+core or other package versions

  • @nestjs/common: 5.6.2
  • @nestjs/core: 5.6.2

Excepted behavior

Classes to not be scanned for all methods

Actual behavior or outcome (for issue)

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
screenshot 2019-02-05 at 15 46 26

We need to make a decision on how to keep the existing functionality and avoid this outcome. First seen here #69 #71

Replication/Example

Default ashPattern

Add a condition to configService.get to return Config class as object when ashPattern === ''. For using with config.get('database');

How to use config service within app.module.ts

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?

ConfigModule.resolveSrcPath prints warning

Issue type:

[x] question
[ ] bug report
[ ] feature request
[ ] documentation issue

nestjs-config version

@nestjs/common+core or other package versions

  • @nestjs/common:
  • @nestjs/core:

Excepted behavior

Actual behavior or outcome (for issue)

Replication/Example

ConfigModule.resolveSrcPath(__dirname).load('config/**/!(*.d).{ts,js}', { path: envPath }),

https://github.com/nestjs-community/nestjs-config/blob/8ebfa857feb6be3004e8fda1a4697eda2476c2b0/src/module/config.module.ts#L7-L10

https://github.com/nestjs-community/nestjs-config/blob/8ebfa857feb6be3004e8fda1a4697eda2476c2b0/src/module/config.service.ts#L186-L226

  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?

Parameter injection decorator doesn't work with interfaces

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.

dependency har-validator can't be installed

Issue type:

[ ] question
[x] bug report
[ ] feature request
[ ] documentation issue

nestjs-config version

@nestjs/common+core or other package versions

  • @nestjs/common:
  • @nestjs/core:

Excepted behavior

Actual behavior or outcome (for issue)

Replication/Example

https://github.com/nestjs-community/nestjs-config/blob/da442274eeef8427d497a8b273a0967fdd3dcf32/package-lock.json#L2900-L2909

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

[Question] load config files from multiple sources

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

Create dynamic providers

Issue type:

[ ] question
[ ] bug report
[ ] feature request
[ ] documentation issue
[x] v2

nestjs-config version

@nestjs/common+core or other package versions

  • @nestjs/common:
  • @nestjs/core:

Add the v2 dynamic providers from github.com/bashleigh/nestjs-config-v2-test

Must be missing something

Issue type:

  • question
  • bug report
  • feature request
  • documentation issue

nestjs-config version

@nestjs/common+core or other package versions

  • @nestjs/common:
  • @nestjs/core:

Excepted behavior

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?

Actual behavior or outcome (for issue)

Replication/Example

error TS7016: Could not find a declaration file for module 'dotenv'.

Issue type:

  • question
  • bug report
  • feature request
  • documentation issue

nestjs-config version
1.4.1

@nestjs/common+core or other package versions

  • @nestjs/common: 6.3.1
  • @nestjs/core: 6.3.1

Excepted behavior

When nestjs-config is added to another project which has the strict flag enabled in its tsconfig.json file, the project fails to build.

Actual behavior or outcome (for issue)

The project which depends on nestjs-config should be built with strict flag enabled in tsconfig.json.

Replication/Example

  • Set strict flag to true on a project which depends on nestjs-config.
  • run tsc.
  • tsc will return:
> 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';
                                      ~~~~~~~~

Add or document support for Webpack HMR

Issue type:

  • question
  • bug report
  • feature request
  • documentation issue

nestjs-config version

1.3.21

@nestjs/common+core or other package versions

  • @nestjs/common: 6.1.0
  • @nestjs/core: 6.1.0

Excepted behavior

Actual behavior or outcome (for issue)

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!

Replication/Example

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.

Add Config class with helper methods

Issue type:

[ ] question
[ ] bug report
[ ] feature request
[ ] documentation issue
[x] v2

nestjs-config version

@nestjs/common+core or other package versions

  • @nestjs/common:
  • @nestjs/core:

Add a class with helpful methods to be created when instancing the module

Add decorator to inject a single parameter

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')

Exception when exporting Winston config

Issue type:

[ ] question
[x] bug report
[ ] feature request
[ ] documentation issue

nestjs-config version
1.2.9

@nestjs/common+core or other package versions

  • @nestjs/common: 5.6.2
  • @nestjs/core: 5.6.2

Excepted behavior

Not throwing an exception

Actual behavior or outcome (for issue)

I am using nest-config with nest-winston, but it seems that new transports.Console() is crashing the ConfigService.

Replication/Example

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>)

Update dependancies

Issue type:

[ ] question
[ ] bug report
[ ] feature request
[ ] documentation issue
[x] v2

nestjs-config version

@nestjs/common+core or other package versions

  • @nestjs/common: 6
  • @nestjs/core: 6

Update all associated packages to github.com/bashleigh/nestjs-config-v2-test

WARNING!! The "modules" key in the @Module() decorator is deprecated and will be removed within next major release. Use the "imports" key instead.

Issue type:

[ ] question
[x] bug report
[ ] feature request
[ ] documentation issue

nestjs-config version
@latest

@nestjs/common+core or other package versions

  • @nestjs/common: 5.7.3
  • @nestjs/core: 5.7.3

Excepted behavior

No warnings

Actual behavior or outcome (for issue)

https://github.com/nestjs/nest/blob/master/packages/common/decorators/modules/module.decorator.ts#L39

WARNING!!
The "modules" key in the @Module() decorator is deprecated and will be removed within next major release. Use the "imports" key instead.

[Reimplementation] Improving the inject-ability with config providers

The idea

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.

The reason

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.

Possible drawback

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 ๐Ÿ‘Ž.

TLDR;

Remove ConfigService injection and instead create a provider for each config file

ConfigModule async provider build

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')],
    }),
  ],
})

Further possibilities

Types

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) {}
}

Without types

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').

Custom env file name

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

static src function doesn't resolve src

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?

[Best Practice] Boolean Values in Config Files

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 modifyConfigName option to README

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

Update nestjs dependancies

Issue type:

  • question
  • bug report
  • feature request
  • documentation issue

nestjs-config version
@latest + @next

@nestjs/common+core or other package versions

  • @nestjs/common:
  • @nestjs/core:

Excepted behavior

Actual behavior or outcome (for issue)

Axios needs updating to v0.19.0 once nestjs/nest#2311 has been released

Replication/Example

Dependancy cleanup

It would be a better idea to set @nestjs/common as a peer dependancy instead of a dependancy

Resolve bad config name because of file separator

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!

Can not pass arguments to dotenv since typescript 3.4.1

Issue type:

  • question
  • bug report
  • feature request
  • documentation issue

nestjs-config version
1.3.21

@nestjs/common+core or other package versions

  • @nestjs/common: 6.1.1
  • @nestjs/core: 6.1.1

Excepted behavior

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.

Actual behavior or outcome (for issue)

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.

Replication/Example

  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`)});

Comment

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

The "this" value of decorated methods gets changed

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.