0

const spgNamespace = io.of("/spg").use(verify());

I tried to find the API of() and use() w.r.t Javascript and socket.io. I am unsuccessful.

I found this link: https://socket.io/docs/v3/namespaces/index.html But they have not explained the use of API of() and use().

I have learnt that of() function is related to promises but this link doesn't have anything related to it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

This SO thread says that use() function is related to adonisJS but my project is not using this library anywhere: what is the 'use' keyword in javascript?

In this code, io is the object of 'socket.io'.

const spgNamespace = io.of("/spg").use(verify());

Please explain what is this line doing and please point out the reference APIs.

Aquarius_Girl
  • 18,558
  • 57
  • 191
  • 353

1 Answers1

1

The method of() as in server.of(nsp) initializes and retrieves the given Namespace.
Find it here : https://socket.io/docs/v3/server-api/#server-of-nsp

The method use() as in namespace.use(fn) registers a middleware function, which is a function that gets executed for every incoming Socket.
Find it here : https://socket.io/docs/v3/server-api/#namespace-use-fn


Your code

const spgNamespace = io.of("/spg").use(verify());

means, you first initialize and retrieve the namespace /spg, and then register a middleware function for retrieved namespace. I see 2 issues here :

  • First : .use() does not return anything (as far as I know), so spgNamespace might turn out undefined;
  • Second : you pass verify() as middleware. Which means you first execute verify function and pass the result into it as middleware. Try only passing the function without executing it like .use(verify) ... instead of .use(verify())
Pascal Lamers
  • 2,152
  • 2
  • 10
  • 30