Designing a CRUD API for WebSockets

2014-02-16

When building Weld, we are using both REST and WebSockets (Socket.io). Three observations on WebSockets:

  1. Since WebSockets are so free-form, you can name events how you want but it will eventually be impossible to debug.
  2. WebSockets don’t have the request/response form of HTTP so sometimes it can be difficult to tell where an event is coming from, or going to.
  3. It would be nice if the WebSockets could fit into the existing MVC structure in the app, preferably using the same controllers as the REST API.

My solution:

  • I have two routing files on my server: routes-rest.js and routes-sockets.js
  • My events look like this example: “AppServer/user/create”.
  • I use forward slashes (“/”) to make the events look like routing paths.
  • The first string is the target (~“host name” if this actually was a path).
  • The second string is the model.
  • The third string is the CRUD verb: i.e. create, read, update, delete.