Created
June 1, 2014 18:32
-
-
Save mikaa123/a9380af5cd1d56a387ce to your computer and use it in GitHub Desktop.
Simple Api implementation
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
var express = require('express'), | |
app = express(); | |
var bodyParser = require('body-parser'); | |
app.use(bodyParser()); | |
var makeResource = require('catnap').makeResource; | |
// This simulates our datastore. | |
var users = [{ | |
id: '1', | |
name: 'foo', | |
email: '[email protected]', | |
salt: 'abc' | |
}, { | |
id: '2', | |
name: 'bar', | |
email: '[email protected]', | |
salt: 'def' | |
}]; | |
users.findById = function (id) { | |
for (var i = 0; i < users.length; ++i) { | |
if (users[i].id === id) return users[i]; | |
} | |
}; | |
/** | |
* User Resource - /users/:userId | |
* Supported action: GET | |
* media type: hal+json | |
*/ | |
var userResource = makeResource('user', '/users/:userId') | |
.representation(function(user) { | |
// Let's filter out the salt here. | |
return { | |
id: user.id, | |
name: user.name, | |
email: user.email, | |
_links: { | |
self: { | |
href: this.path.replace(':userId', user.id) | |
} | |
} | |
}; | |
}) | |
.representation('partial', function(user) { | |
return { | |
id: user.id, | |
name: user.name, | |
_links: { | |
self: { | |
href: this.path.replace(':userId', user.id) | |
} | |
} | |
}; | |
}) | |
.get(function(req, res) { | |
var user = users.findById(req.params.userId); | |
if (!user) { | |
return res.send(400); | |
} | |
return res.send(200, userResource(user)); | |
}) | |
.attachTo(app); | |
/** | |
* Users Resource - /users | |
* Supported action: GET, POST | |
* media type: hal+json | |
*/ | |
var usersResource = makeResource('users', '/users') | |
.representation(function (users) { | |
return { | |
count: users.length, | |
_embedded: { | |
users: users.map(function (user) { | |
return userResource(user, 'partial'); | |
}) | |
} | |
}; | |
}) | |
.get(function (req, res) { | |
res.send(200, usersResource(users)); | |
}) | |
.post(function (req, res, next) { | |
var newUser = req.body; | |
console.log(newUser); | |
users.push(newUser); | |
res.send(201, userResource(newUser)); | |
}) | |
.attachTo(app); | |
var server = app.listen(3001, function() { | |
console.log('Listening on port %d', server.address().port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment