Skip to content

Instantly share code, notes, and snippets.

@istro
Created January 27, 2014 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save istro/8658348 to your computer and use it in GitHub Desktop.
Save istro/8658348 to your computer and use it in GitHub Desktop.
////// EXAMPLE
module.exports = function (server) {
// Create an API namespace, so that the root does not
// have to be repeated for each end point.
server.namespace('/api', function () {
// Return fixture data for '/api/posts/:id'
server.get('/posts/:id', function (req, res) {
var post = {
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": ["1", "2"],
"user": "dhh"
},
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
};
res.send(post);
});
});
};
//////// MY FIRST IMPLEMENTATION
var path = require('path');
var fs = require('fs');
// going two peer directory of lightfixtures repo
var fixtureDir = path.resolve(__dirname, '../..', 'lightfixtures')
module.exports = function (server) {
// Create an API namespace, so that the root does not
// have to be repeated for each end point.
server.namespace('/api', function () {
var locationsProtocol = JSON.parse(fs.readFileSync(fixtureDir + '/locations.json'));
var roomsProtocol = JSON.parse(fs.readFileSync(fixtureDir + '/rooms.json'));
// stub location list request
server.get(locationsProtocol[0].request.url, function (req, res) {
res.send(locationsProtocol[0].response.data);
});
// stub individual location request
server.get(locationsProtocol[1].request.url, function (req, res) {
res.send(locationsProtocol[1].response.data);
});
// stub room list request
server.get(roomsProtocol[0].request.url, function (req, res) {
res.send(roomsProtocol[0].response.data);
});
// stub individual room request
server.get(roomsProtocol[1].request.url, function (req, res) {
res.send(roomsProtocol[1].response.data);
});
});
};
/////////////// Something I'd like to do instead
var path = require('path');
var fs = require('fs');
// going two peer directory of lightfixtures repo
var fixtureDir = path.resolve(__dirname, '../..', 'lightfixtures')
module.exports = function (server) {
// Create an API namespace, so that the root does not
// have to be repeated for each end point.
server.namespace('/api', function () {
var locationsProtocol = JSON.parse(fs.readFileSync(fixtureDir + '/locations.json'));
var roomsProtocol = JSON.parse(fs.readFileSync(fixtureDir + '/rooms.json'));
function respondToEach(json) {
for (var i = 0; i < json.length; i++) {
server.get(json[i].request.url, function (req, res) {
res.send(json[i].response.data);
});
}
}
respondToEach(locationsProtocol);
respondToEach(roomsProtocol);
});
};
@istro
Copy link
Author

istro commented Jan 28, 2014

It turned out to be a scoping issue. Stackoverflow FTW!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment