ajaybc
ajaybc

Reputation: 4059

How do I route websocket requests to SailsJS without breaking the built in abstraction

I am new to SailsJS and I am building an API for a iOS application. As per the SailsJS documentation it provides and abstraction for the Socket IO requests and routes it to my controllers. For example if I emit some data to /user/create it will automatically call the UserController -> create function. From what I understood I need to use the sails.io.js file on client side and emit using Socket.get and Socket.post.

As I am using this as an API for an iOS where iOS app is the client, how do I emit data to the server while using the routing feature in Sails JS ?

Upvotes: 2

Views: 914

Answers (1)

sgress454
sgress454

Reputation: 24948

If you look at the source code for sails.io.js, you'll see it's just a bunch of helper methods thinly wrapping the Socket.io client. The upshot is, you can still use Sails' wonderful routing-over-sockets mechanism using regular socket.emit calls. Just use the HTTP method as the event name, and send the URL and data as the payload. For example:

socket.emit('get', {url: 'http://example.com/foo'}, cb);
socket.emit('post', {url: 'http://example.com/bar', data: {name: 'joe'}}, cb);

where cb is a callback that will receive the result of the call as its sole argument.

Upcoming versions of Sails will support a second argument to the callback which contains more data about the response, like a status code and errors.

Upvotes: 3

Related Questions