我创建了以下db_postgres
服务,效果很好。
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();
}
}
}
案例:
问题: 最简单,最简单的方法是什么?
我的努力:
getUsers()
服务中删除了db_postgres
操作。queries
服务,如下所示: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() {}
}
问题:
"db_postgres"
中添加dependencies
并运行npm run dev
时
即moleculer-runner --env --hot --repl services
,
db_postgres
服务正在正常注册。
但是,queries
服务永远不会。终端中的流量冻结,并且光标闪烁。
为什么?db_postgres
中添加mixins
时,出现以下错误
Failed to load service '.../services/queries.service.js' ReferenceError: db_postgres is not defined
为什么?Tia
答案 0 :(得分:0)
您应该向db_postgres
加载require并用作混合,而不是依赖。