我创建了两个服务类。下面是ShellService类定义。
class ShellService {
create(data, params) {
if (Array.isArray(data)) {
return Promise.all(data.map(current => this.create(current)));
}
let hostname=params.query.hostname
let port = params.query.port
const id = _.uniqueId();
this.shells[id] = spawn('mongo', ['--host', hostname, '--port', port]);
return Promise.resolve({id});
}
...
}
module.exports = function() {
// Initialize our service with any options it requires
let service =new ShellService()
return service;
};
在其create方法中,它创建一个shell实例并将其添加到其shell数组对象上。我有另一个休息服务类,并希望访问shells数组对象。我怎样才能做到这一点?我在下面尝试但没有工作:
const shellService = require('../shell-service')
class SocketService {
...
我声明了SocketService
类并要求shell服务。但我无法在shellService.XXXX
课程中致电SocketService
。我该怎么做才能实现这个目标?
答案 0 :(得分:1)
由于您已经在this.shells[id]
中存储了shell引用,因此您可能希望实现一个.find
service method,它返回所有可用shell的列表:
class ShellService {
find() {
const shellProcesses = this.shells;
const shells = Object.keys(shellProcesses).map(key => {
const shell = shellProcesses[key];
return {
id: shell.pid
}
});
return Promise.resolve(shells);
}
create(data, params) {
if (Array.isArray(data)) {
return Promise.all(data.map(current => this.create(current)));
}
let hostname=params.query.hostname
let port = params.query.port
const id = _.uniqueId();
this.shells[id] = spawn('mongo', ['--host', hostname, '--port', port]);
return Promise.resolve({id});
}
}
module.exports = function() {
// Initialize our service with any options it requires
let service =new ShellService()
return service;
};
注册为Feathers服务后,您可以使用app.service('shells').find().then(shellInfo => )
。