Skip to content

Instantly share code, notes, and snippets.

@projectweekend
Created November 18, 2013 00:48
Show Gist options
  • Save projectweekend/7520574 to your computer and use it in GitHub Desktop.
Save projectweekend/7520574 to your computer and use it in GitHub Desktop.
Node.js Read-only Socket - A reusable pattern I'm testing out to for a socket that handles read-only actions against a model.
module.exports = function (socket, handleError, config) {
// set some common items we will need from config
var route = config.route;
var model = config.model;
socket.on(route, function (data) {
switch (data.action) {
case 'list':
model.find(data.query, function (err, itemList) {
if (err) {
return handleError(route, err);
}
var response = {
items: itemList
};
socket.emit(route + ':list:success', response);
});
break;
case 'item':
model.findOne(data.query, function (err, singleItem) {
if (err) {
return handleError(route, err);
}
var response = {
items: [singleItem]
};
socket.emit(route + ':item:success', response);
});
break;
default:
err = {
message:"available actions are: 'list' & 'item'."
};
handleError(route, err);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment