Comments (12)
export class AppModule {
static port: string
constructor(configService: ConfigService) {
AppModule.port = configService.get('HTTP_PORT')
}
}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(AppModule.port || 3000);
}
bootstrap();
from schematics.
Thank you @erikkrieg.
Just to explain. Using ConfigService
outside of the application context is possible, but is not (always) considered as a best practice. Basically, ConfigService
should be used within your application so you can easily mock/override it in your tests. Nonetheless, there is nothing wrong with using process.env
directly in your main.ts
which you will very likely don't test at all.
from schematics.
In this case, the port that the server listens on
Well, that might be a good thing actually. I thought you wanted to suggest the usage of the ConfigService
explicitly. I think that we could change the schematic, so it will generate this:
app.listen(process.env.PORT || 3000)
(instead of just hardcoded port)
from schematics.
Actually, there is a popular npm package (https://github.com/lorenwest/node-config) that allows you to define config files for different "environments" and at runtime it will pick the config matching NODE_ENV
. I think this sufficiently abstracts the configuration process and makes it fairly easy to switch environments (see the README examples). As @kamilmysliwiec noted, it is fine that this aspect of the configuration mechanism is not provided as a service since the bootstrap()
is out of the DI-scope anyways. Of course, nonetheless, nothing prevents you from wrapping the config mechanism in a service to provide it to other parts of your app later.
from schematics.
I also just wanted to thank the contributors of this project for working towards addressing the lack of strong convention in the Node server-side ecosystem ❤️
from schematics.
@felixhayashi yes this works ....thank you so much, especially the fact that node-config has a feature of
Custom Env variables
It took me a while to realise that I need to keep the config
folder outside the src
folder and then it worked beautifully. Thank you
from schematics.
Many people use .env but I have been not saw who think about why we should use .env at first time and why there are people that use as .env.bak
.
Generally sensitive data should be not exposed in some file or and should be not tracked.
Of source, I can understand always setting vars is to be tedious too (or maybe we should patch encrypted vars dynamically with big working).
But tracking or maintaining env vars on source, it means injector is not only one like pm2 ecosystem json or something in future. then it also means config service cannot be fixed.
Moreover, Nowadays on javascript, pm2 is used on dev / staging env normally.
Maybe you don't need to use .env except on local env.
Finally I think, it is ok this issue is closed.
from schematics.
I have gone through official nestjs documentation. Here is what should be done
in main.ts-
import { ConfigService } from '@nestjs/config';
const port = configService.get('PORT');
await app.listen(port|3000);
in .env
PORT=3000
In app.module.ts , import config module if not done ;-)
@module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
]
})
from schematics.
@erikkrieg Please review an example in nestjs/nest#1573
After this is polished and merged, same changes could be applied to Nest CLI as well.
from schematics.
I am unsure why the issue has been closed. Might be a misunderstanding on what I was trying to communicate, or perhaps something I am missing about the CLI.
I don't really know this framework well enough to have an opinion on how this project handles configuration so I referred to the ConfigService
class because that is what is used in the docs to showcase this best practice.
To clarify the issue I was pointing to, my concern is that the CLI creates a new project that lacks a good convention for handling configuration. In this case, the port that the server listens on. This implicitly promotes an anti-pattern and misses an opportunity to share the opinions that project already seems to have on how to handle configuration.
The Node ecosystem is sorely missing a strong, opinionated framework like what Rails is to Ruby. I hope that this project is aspiring to fill that void. I think having the CLI get devs started without having to think about setting conventions like this helps get there.
from schematics.
Yeah, that is a step in the direction I was trying to communicate. Ofc it is up to the maintainers to determine how sophisticated the handling of config in the "basic" project generated from the CLI should be.
from schematics.
Hey firstly @kamilmysliwiec, great job on this project; I'm enjoying working with it :).
Using something like app.listen(process.env.PORT || 3000)
assumes that the env variable is configured and available for this app. Considering this schematic is likely to be used for creating multiple projects we will likely still need to end up changing this.
I've happened to solve this for our custom schematic that extends this in order to add some business specifics.
By utilizing environments files(As Angular does) and schema properties in combination, we are able to generate and run multiple nest apps straight from the cli with no additional config. I think something along these lines could provide an elegant solution.
Example:
We set the environment.prod file to expose a server_port property to a environment variable.
export const environment = { production: true, server_port: process.env'<%=name%>-port'] };
And in the dev environment file we used a port chosen at the generate stage.
export const environment = { production: false, server_port: '<%=port%>' };
The schema.json sets the default and prompts for a choice
"port": { "description": "The dev port this server should run on.", "type": "string", "default": "3333", "x-prompt": "What port would you like to use for the app?" },
In our main.ts we just import import { environment } from './environments/environment';
and use it like app.listen(environment.server_port, () => {});
from schematics.
Related Issues (20)
- Add .env to generated .gitignore file HOT 3
- Using async method and `ParseIntPipe` for generated resources controllers and services[restful] . HOT 8
- Routing module when create resource HOT 4
- When converting project to a monorepo configure all E2E tests to be run HOT 1
- Switching to Monorepo dry run bug HOT 8
- Upgrade peer dependency range to allow typescript v5 HOT 5
- error when invoking 'generate module' and there's no nestjs module to update HOT 1
- Outdated schema file for nest-cli.json HOT 2
- nest cli generate resource missing trailing comma HOT 1
- Create a Nest workspace without creating a Nest application HOT 1
- Error when using 'application' generator in a directory that doesn't has the 'test' folder HOT 1
- use default library prefix HOT 1
- Dependency Dashboard HOT 1
- "source-map-support" not declared as dependency breaks if using yarn with pnp HOT 3
- Vulnerable dependency: ansi-regex HOT 1
- Warning about unsupported version of `@angular-devkit/core` on `LTS/gallium` HOT 2
- Strict mode by default HOT 2
- Schematics aliases HOT 4
- Gateway: output is generated in wrong directory HOT 8
- Generate resource command creates schema.gql file without the findAll Query that has been generated in the resolver HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from schematics.