Loopback 4: Specify environment var in the #model - mongodb

I am trying to get the mongodb collection name from an environment variable defined in .env. It looks like the model is initialised before the .env is read.
#model({
name: 'MyType',
settings: {
mongodb: process.env.COLLECTION_NAME,
},
})
The process.env.COLLECTION_NAME is, at this point, undefined
Any way to externalised the collection name?
Many thanks for the help.

By default, Node.js does not read from .env.
To read from .env, we need to utilize the dotenv package.
Since models are resolved through the Booter during startup, hence we need to call dotenv.config() before app.boot().
Update index.ts as follows:
// At the top of the file
import dotenv from 'dotenv';
...
// Inside the main function
// dotenv.config() must appear before app.boot()
dotenv.config()
...
app.boot();
app.start();
This would cause dotenv to overwrite process.env with the values in .env where necessary.
Further reading:
https://www.npmjs.com/package/dotenv
How do I setup the dotenv file in Node.js?

in your
src/index.ts
import {ApplicationConfig, MyApplication} from './application';
require('dotenv').config();
export * from './application';
and your .env file in the "root" of your project

Related

How to put a Mongo Db URL in dotenv file?

I'm trying to add environment file to a node project, and I have put mongo URL in it, now, when I console log it, prints undefined... anyone know where's the problem?
require("dotenv").config();
let MONGO_URL = process.env.MONGO_DB_URL;
console.log("MONGO", process.env.MONGO_DB_URL);
dotenv file
MONGO_DB_URL="mongo URL"
if I print
console.log(require('dotenv'.config()))
CONFIG { parsed: { MONGO_DB_URL: '' } }
check if you had install npm package of dotenv
if yes then it will work else you need to install it
npm i dotenv
in .env file
MONGO_DB_URL= mongodb://localhost:27017
in index file or wherever u want
require("dotenv").config();
let MONGO_URL = process.env.MONGO_DB_URL;

Verify JWT Token error 'secretOrPrivateKey must have a value'

return failure(new Error('secretOrPrivateKey must have a value'));enter image description here
I think your application is not able to read the environnement variables.
I advice you to use the package dotenv : https://github.com/motdotla/dotenv
After installing it you have to import it at the top of your application like this:
require("dotenv").config();
Specify a file .env at the root of your application and add your variables
JWT_SECRET=12bob12ou2b1ob
NODE_ENV=development
After, you can use the variables like you did in your linked image:
const jwtSecret = process.env.JWT_SECRET

Scala config lookup secrets

I have application.conf file which contains secrets(password for DB etc..) And this secret will be mounted as a file(the file content will contain the actual secrets) in the running pod. How can scala config library be tweaked to handle this. i.e
instead of normal application.conf
db {
user = "username"
password = "xxx"
}
I would have something like this...
db {
user = "username"
password = "${file_location}"
}
As the file is parsed, it should identify that the value of key password, needs to be resolved by looking up the file and loading its contents.
A simple function can be written to load the content of this file, how can this is be integrated with seamlessly with scala config. ie. The rest of the code will continue to use
config.getString(db.password)
I assume you are using configuration of HOCON format and Typesafe configuration library for it.
I don't think it has such feature out of the box, but as an possible alternative you can take a look at include feature - you can include content of another file into your application.conf:
db {
user = "username"
}
include /path/to/pod.conf //include env specific configuration file
and put inside /path/to/pod.conf:
db {
password = "pod_db_pass"
}
So eventually contents of both files will be merged inside application during loading, and your final config will contain password at path db.password
UPDATE
Another possible option load password from file and merge into config file with withFallback method. Example:
import com.typesafe.config._
val passord = "password_from_file"
val passwordConfig = ConfigFactory.parseString(s"db.password=$passord")
val applicationConfig = ConfigFactory.parseString(s"db.user=db_user")// Replace this with `ConfigFactory.load()`
val config = applicationConfig.withFallback(passwordConfig)
println(config)
Printout result:
Config(SimpleConfigObject({"db":{"password":"password_from_file","user":"db_user"}}))
Scatie: https://scastie.scala-lang.org/WW3weuqiT9WRUKfdrZgwcw

Scala Config: Include another file.conf

Currently, I have a resources/application.conf file which has the following keys:
development {
server = www.myapp.com
aws_key = my_aws_key
aws_secret = my_aws_secret
}
I would like to remove my aws_key and aws_secret from the file.
I was thinking of creating another file called resources/credentials.conf and storing my personal authentications there.
credentials {
aws_key = my_aws_key
aws_secret = my_aws_secret
}
and then include it some way in my application.conf or merge that config to the Config object in addition to application.conf.
credentials.conf would be git ignored. A sample file would be checked in credentials-sample.conf which each developer would change according to his own credentials and rename the sample file to credentials.conf
I tried different variation of include like
include "credentials"
include "credentials.conf"
include "./credentials.conf"
include file("./credentials.conf")
and so on.
I know I can pass it via system variables but I would like to try it like mentioned above. If you know of a better way, please let me know.
Typesafe Config provide the way to fallback from one configuration to another. You can try the ConfigFactory.Load() to load different config and use withFallback to line them up in your designated order. Such as:
ConfigFactory.Load("credentials.conf") withFallback ConfigFactory.Load("application.conf")
Inside your conf file, add
include "another_file.conf"
ie: https://github.com/cicco94/scala-akka-slick-demo/blob/master/src/main/resources/application.conf

sails.js Is it possible to set process.env variables from application?

I am trying to use npm module fb to use facebook api. The config file is located in the module and here is the snapshot of the same
var config = { };
// should end in /
config.rootUrl = process.env.ROOT_URL || 'http://localhost:3000/';
config.facebook = {
appId: process.env.FACEBOOK_APPID || '130243393813697',
appSecret: process.env.FACEBOOK_APPSECRET || 'c82696768ae4ad8b63db874cb64eb558',
appNamespace: process.env.FACEBOOK_APPNAMESPACE || 'nodescrumptious',
redirectUri: process.env.FACEBOOK_REDIRECTURI || config.rootUrl + 'login/callback'
};
module.exports = config;
I don't wish to change the config file of the module since node_modules folder is kept in the gitignore list. For configuring the module to use my app's appId and appSecret, I need to set the process.env variables FACEBOOK_APPID and FACEBOOK_APPSECRET
I understand that it can be done while calling the sails lift but is it by any means possible to set these values inside the app so that I only have to call
sails lift
without any of those variables and those should be set automatically ? Or what is the best way to achieve what I am trying to do here ?
You should set the environment-variables outside of your App.
Instead of sails lift you could also use node app.js. With that you can define environment-variables for your node-application with:
$> FOO='bar' node app.js
In your case:
$> FACEBOOK_APPID='232322a22' FACEBOOK_APPSECRET='mysecrete' node app.js
If you want to set this vars in your app (I wouldn't suggest that!) you could set them before including your npm-module. For example in your config/bootstrap.js:
module.exports.bootstrap = function(cb) {
process.env.FACEBOOK_APPID = "myvar";
process.env.FACEBOOK_APPSECRET = "mysecrete";
sails.facebook = require("yourmodule");
cb();
};
Here is a good link for setting environment variables when "Production", "Staging" and "Development" in Sails feels fragmented.
Here is a quick video tutorial which simply explains how to create environment variables in node.js
Step1:
Install the package dotenv as dependency
$ npm install dotenv --save
Step2:
Then require dotenv in app.js and load the .env file
var dotenv = require('dotenv');
dotenv.load();
Step3:
Create a .env file in the root folder (ie. at the same document level as app.js file)
Step4:
Add your environment variables
S3_KEY=enfiownqefniqofewqofnieqwvewlk
S3_SECRET=123456789
Now you can access those environment variables anywhere in the app (probably in some config/ files):
return {
key: process.env.S3_KEY,
secret: process.env.S3_SECRET,
region: 's3-eu-west-1',
bucket: 'myBucket',
s3params: {
ACL: 'public-read'
}
}
Credit goes to Noah Bass for providing this tutorial.