Documentation, Uncategorized

Multiple Environments with Loopback 4

When configuring multiple environments for a Loopback 4 Application, it can appear less straight forward than with Loopback 3, so here is a quick fix for how to get over this obstacle as elegantly as possible in 5 minutes.

  1. Import dotenv and create a .env file in the root of the app.
  2. Put your database configuration in this file.
  3. Empty the existing datasource file so it contains an empty JSON (file is required by compiler and the bootstrapping).
  4. Add the code below to the application.ts file in the src directory.
  5. Don’t forget to require the dotenv from the run command.
this.bind('datasources.default').to(new DefaultDataSource());
this.dataSource(new DefaultDataSource());
this.bind('datasources.config.default').to({
  name: 'default',
  connector: 'mongodb',
  hostname: process.env.DB_DEFAULT_HOSTNAME,
  port: process.env.DB_DEFAULT_PORT,
  user: process.env.DB_DEFAULT_USER,
  password: process.env.DB_DEFAULT_PASSWORD,
  database: process.env.DB_DEFAULT_DATABASE,
  useNewUrlParser: process.env.DB_DEFAULT_USENEWURLPARSER,
  authSource: process.env.DB_DEFAULT_AUTHSOURCE
});
this.bind('datasources.default').toClass(DefaultDataSource);

This is a quick fix intended to help move on if in a pickle, I will refine this further so the application will check the process.env.NODE_ENV variable instead and load the corresponding file.

For the original inspiration to this post, head over here: https://medium.com/p/8f085399268/responses/show

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s