How can I use external configuration parameters (not part of molecular.config.js) to be used in mixins or services #1110
-
Hi All,
In same way we have created a mixin for connecting database . So how can we paas db url for different environments through docker-compose.env Note : I tried to see metadata tags, but is it correct way to use for both mixin and services. Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
When I develop new microservices or types of microservices for my team we generally use the process environment variable approach in order to adhere to factor 3 of the 12 factor app. Generally, this is as simple as referencing the process environment variable in the microservice settings object and using it elsewhere: // keycloak.service.js
module.exports = {
name: "keycloak",
settings: {
keycloakUrl: process.env.KEYCLOAK_URL,
},
action: {
doSomething(ctx) {
callKeycloakAPI(this.settings.keycloakUrl);
}
},
} I tend to take the same approach with secrets but leverage Moleculer's secure service settings feature which allows you to prevent the sharing of certain service settings with other nodes or the service registry. Additionally, I regularly use the following utility function (or a variant) to ensure any required environment variables are set. The function helps with type safety if using TypeScript and throws an error during schema generation which should cause early failure and service termination (another principal I generally like to adhere to in order to avoid/limit prolonged failure modes). /**
* Retrieve the value of an environment variable or throw an error if it does
* not exist in the current process.
*
* @param name the name of the expected environment varible
* @param message an optional additional message
*/
export function envvarOrError(
/**
* The name of the environment variable to attempt to obtain from the
* process environment.
*/
name: string,
/**
* Supplemental error message in addition to default message.
*/
message?: string,
) {
const envar = process.env[name];
if (!envar) {
throw new Error(
`expected environment variable '${name}' is undefined${message ? `; ${message}` : ''}`
);
}
return envar;
} Used in the service example above: // keycloak.service.js
module.exports = {
name: "keycloak",
settings: {
keycloakUrl: envvarOrError('KEYCLOAK_URL', 'keycloak API URL is required'),
},
action: {
doSomething(ctx) {
callKeycloakAPI(this.settings.keycloakUrl);
}
},
} Hope this helps! |
Beta Was this translation helpful? Give feedback.
When I develop new microservices or types of microservices for my team we generally use the process environment variable approach in order to adhere to factor 3 of the 12 factor app.
Generally, this is as simple as referencing the process environment variable in the microservice settings object and using it elsewhere:
I tend to take the same approach with secrets but leverage Moleculer's secure service settings feature which allows you to prev…