Created
November 18, 2013 00:48
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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