How to share data among services in nodejs

500 views Asked by At

I created two service classes. Below is the ShellService class definition.

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;
};

In its create method, it creates a shell instance and add it on its shells array object. I have another rest service class and want to access the shells array object. How can I do that? I tried below but not work:

const shellService = require('../shell-service')
class SocketService {
  ...

I declared SocketService class and require the shell service. But I can't call shellService.XXXX in my SocketService class. What should I do to achieve this?

1

There are 1 answers

2
Daff On BEST ANSWER

Since you are already storing the shell reference in this.shells[id] you probably want to implement a .find service method that returns a list of all available shells:

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;
};

Once registered as a Feathers service you can then use app.service('shells').find().then(shellInfo => ).