Is there any name convention for response event in socketIO?

Viewed 1002

For example, the client site emits the event "getAllBooks". The server receives this event, create another internal event with a correlation id to the original event and puts it to queue for handling on another part of the backend. Then acks the event "getAllBooks". Backend process internal event and is ready to emit a response event for "getAllBooks" event. Is there any name convention for this response event? I prefer to use postfix "Response" for these case it would be "getAllBooksResponse", but I saw in some projects that there used the original name.

UPDATE: communication diagram

For better understanding, I attached a simple diagram. My question is: in case 3 and 4, is better to use "GetAllBooksResponse" or "GetAllBooksReplay" instead of "GetAllBooks" ?

1 Answers

There is not a known event name convention since the event names are simply strings.

Altho there are some scenarios that we can talk on.

Let say client just trying to send an emit and gets a response from server.

If the server is just gonna return back to the original client and not others what I'm usually doing is using callbacks such as:

// client.js
socket.emit('getAllBooks', function(books) {
  console.log(books) // comes from server side!
});

// server.js
socket.on('getAllBooks', function (callback) {
  callback([ 'Book 1', 'Book 2' ]); // sending it to client side.
});

For this method please note that callback has to come as the "last argument" to the server side. For more info please check Acknowledgements from socket.io's docs.


So another scenario is sending multiple clients.From this point I usually create a mapper object for my events and use it as a single point of truth

const prefix = 'MyGamePrefixToBeAbleToSeperateEventNames' //:)
const EVENTS = {
  INITIALIZE: `${prefix}Initialize`,
  JOIN: `${prefix}Join`,
  SET_USER_COUNT: `${prefix}SetUserCount`,
  // and more events...
};

So atleats with this way I have a place where I can update every event-name at once. To your question about adding 'Response' at start or end, I also don't have a certain rules but I'm usually using get... and set....

socket.on(EVENTS.INITIALIZE, () => {
  socket.on(EVENTS.JOIN, () => {
    userCount++;
    // how ever you wanna use :)
    socket.broadcast.emit(EVENTS.SET_USER_COUNT, userCount);
    io.emit(EVENTS.SET_USER_COUNT, userCount);
  });
});

After everything I'm usually coping the EVENTS object to client side and use the same event names. This means obv. you need to keep track of snyc :D

Hope I gave some ideas :)

Related