I am currently using Node.js as a server (Express.js) and AngularJs in client side, switched from HTTP-based API to WebSockets (using Socket.io) due for the performance improvement.
Since WebSockets lacks of status codes/errors management and simply returns JSON with an optional callback, I have to implement this error management. I want a consistant behaviour when an error occurs, and instead of making this error check manually I want to wrap it to reduce the boilplate in my code using Promises over the bad old callback-based.
For example instead of using raw socket.io in angular:
socket.emit('users/read', {id: 2}, function handleResponse(res){
if(res.success){
var user = res.data;
socket.emit('projects/by-user', {userId: user.id}, function handleResponse(res){
if(res.success){
var projects = res.data;
// Do something with the data
} else{
// Error getting user's projects
console.log(res.error)
}
})
} else{
// Error getting user
console.log(res.error)
}
})
I would like to have something like this:
webSocketClient
.request('users/read', {id:2})
.then(function(user){
return webSocketClient.request('projects/by-user', {userId: user.id})
})
.then(function(projects){
// Do something with projects
})
.catch(function(err){
// Something went bad
})
What is the recommended JSON structure when implementing a request-response WebSockets-based API? Or there is a library that can do this for me?
I am currently thinks about a JSON with this structure in response:
{
success: true/false,
data: [if exists],
statusCode: [default 200 for success or 500 for failure],
error: [if exists]
}
I think that working with WebSockets using Promises instead of callbacks is a fundamental and obious requirement, but for some reason all the libraries I found didn't wrapped the callbacks with Promises, which leads me to the question if I am missing the something?
Thanks