I have created the following db_postgres
service which works fine.
db_postgres.service.js
"use strict";
const Promise = require('bluebird');
const initOptions = {
promiseLib: Promise,
capSQL: true
};
const pgp = require('pg-promise')(initOptions);
const cn_postgres = {
host: 'localhost',
port: 5432,
database: 'db_name',
user: 'user_name',
password: 'user_password',
...
};
var db_postgres = null;
module.exports = {
name: "db_postgres",
version: "",
mixins: [],
hooks: {},
settings: {},
metadata: {},
dependencies: [],
actions: {
getUsers() {
db_postgres.any('SELECT * FROM user')
.then(data => {
return console.log(data);
})
.catch(error => {
return console.log(error);
});
},
},
methods: {},
events: {},
created() {},
async started() {
return db_postgres = await pgp(cn_postgres);
},
async stopped() {
if (db_postgres) {
return db_postgres.$pool.end();
}
}
}
Case:
- I have a large number of actions.
- I would like to create more instances of this service, but unfortunately, it is not possible since I get a warning/error about establishing a new connection that already exists.
- I do not wish to use any ORM-based solution.
- I wish to avoid using any wrapper function(s) and maintain a DRY manner as much as possible.
Question: What is the simplest and easiest way to do that?
My effort:
- I removed the
getUsers()
action fromdb_postgres
service. - I created a new
queries
service as follows:
queries.service.js
"use strict";
module.exports = {
name: "queries",
version: "",
mixins: [db_postgres],
hooks: {},
settings: {},
metadata: {},
dependencies: ["db_postgres"],
actions: {
getUsers() {
db_postgres.any('SELECT * FROM user')
.then(data => {
return console.log(data);
})
.catch(error => {
return console.log(error);
});
},
},
methods: {},
events: {},
created() {},
async started() {},
async stopped() {}
}
Problems:
- When I add
"db_postgres"
independencies
and runnpm run dev
iemoleculer-runner --env --hot --repl services
, thedb_postgres
service is being registered normally. But,queries
service is never. The flow in terminal freezes and cursor is blinking. Why? - Next, when I also add
db_postgres
inmixins
I get the following errorFailed to load service '.../services/queries.service.js' ReferenceError: db_postgres is not defined
Why?
Tia