如何知道feather-client连接到服务的时间

时间:2017-05-24 13:57:26

标签: feathersjs

我正在尝试测试一个事件过滤器但是有一个时间问题,我不知道如何解决。除了在setTimeout中包装REST请求之外,我怎么能让它工作?

const app = require('../../src/app');

const feathers = require('feathers/client')
const socketio = require('feathers-socketio/client');
const hooks = require('feathers-hooks');
const io = require('socket.io-client');

const rp = require('request-promise');

const service = app.service('users');

let server = null;

describe('\'users\' service', () => {
  beforeEach((done) => {
    server = app.listen('3030');
    server.once('listening', done);
  });

  afterEach((done) => {
    server.close(done);
  });

  it('returns stuff #test', (done) => {
    const socket = io('http://localhost:3030');
    const app = feathers()
      .configure(hooks())
      .configure(socketio(socket));

    const messageService = app.service('users');
    messageService.on('created', message => {
      console.log('Created a message', message);
      done();
    });

    socket.on('connection', () => {
      // 
      // The messageService is not connected yet
      //   so messages.filters.js will not fire
      // 
      // Giving it a chance to connect with setTimeout does work... 
      //           setTimeout(() => {
        rp({
          method: 'POST',
          url: 'http://localhost:3030/users',
          body: {
            test: 'Message from REST'
          },
          json: true
        });
      //           }, 500);
    });

  });
});

我尝试用这些替换socket.on

  • messageService.on('connection'
  • service.on('connection'(基于Node.js EventEmitter)
  • 等......

修改

我已经发现service.on('newListener'可以正常工作,但它被多次触发。我需要追踪单一连接:

const messageService = app.service('users');
messageService.on('created', message => {
  console.log('Created a message', message);
  done();
});

1 个答案:

答案 0 :(得分:0)

它只是service.on('newListener'

https://nodejs.org/api/events.html#events_event_newlistener

  

为“< newListener”注册的听众event将传递事件名称和对要添加的侦听器的引用。

然而,当我实现这一点时,我发现它正在收听5个不同的事件。所以,你需要过滤掉那些:

service.on('newListener', (event, listener) => {
  if (event === 'created') {
    rp({
      method: 'POST',
      url: 'http://localhost:3030/users',
      body: {
        test: 'Message from REST'
      },
      json: true
    });
  }
});