musicformellons
musicformellons

Reputation: 13383

feathersjs sockets using events

In the feathersjs docs, e.g. here, recommended way to call the server is by emitting an event. Why not just directly make the app call? So why use:

socket.emit('find', 'messages', { status: 'read', user: 10 }, (error, data) => {
  console.log('Found all messages', data);
});

When you can simply do:

app.service('messages').find({ query: { status: 'read', user: 10 } }) 

Is this just people preferring the event notation or are there other arguments to consider?

Upvotes: 0

Views: 233

Answers (1)

Daff
Daff

Reputation: 44215

The documentation page you linked explains how to use the websocket directly - for example if you connect with an Android app or don't want to/can't use Feathers on the client.

It is recommended to use Feathers on the client whenever possible and it does the exact same thing for you automatically under the hood. A client code like this:

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

const socket = io('http://api.my-feathers-server.com');
const app = feathers().configure(socketio(socket));

app.service('messages').find({ query: { status: 'read', user: 10 } })
  .then(data => console.log('Found all messages', data));

Does the exact same thing as

const io = require('socket.io-client');
const socket = io('http://api.my-feathers-server.com');

socket.emit('find', 'messages', { status: 'read', user: 10 }, (error, data) => {
  console.log('Found all messages', data);
});

But with the first you get the goodness (hooks, events, promises, authentication) and familiarity of a Feathers app.

Upvotes: 2

Related Questions