fixed PUT overwriting user, fixed query parsing error

This commit is contained in:
Ritchie Martori
2012-04-26 15:51:55 -07:00
parent 571ece3755
commit 5ea6b9780e
4 changed files with 23 additions and 9 deletions

View File

@@ -24,7 +24,11 @@ var router = module.exports = function (req, res, next) {
// query sugar for JSON based query strings
// eg ?q={"foo": {"bar": true}}
if(req.query && req.query.q && req.query.q[0] === '{') {
req.query = JSON.parse(req.query.q);
try {
req.query = JSON.parse(req.query.q);
} catch(e) {
return next({message: 'Error when parsing query: ' + e.message, status: 400});
}
// mixin orderby support
if (req.query.$orderby) {
req.sort = req.query.$orderby;

View File

@@ -12,9 +12,9 @@ module.exports = function (req, res, next) {
// support separate collections for each type of user
var col = require('./collection').use(req.resource.path);
// TODO change index of to something re-usable
if(~req.url.indexOf('/login')) {
if(req.method != 'POST') {
// refuse login request from other methods
return next({status: 404});
}
@@ -68,6 +68,15 @@ module.exports = function (req, res, next) {
if(req.method != 'POST' && !req.query._id && !req.isRoot) {
return next({message: 'Must include an _id when querying or updating a user'});
} else {
// update should only set properties (not overwrite the entire object)
if(req.method === 'PUT') {
var data = req.data || req.body;
delete data._id;
req.body = req.data = {
$set: data
};
}
col.exec(req, function (err, docs) {
res.data = docs;

View File

@@ -30,7 +30,7 @@ describe('Static', function(){
, out = fs.createWriteStream(__dirname + '/support/out-eg.jpg')
;
client.use('/avatars/eg.jpg').post(file, function (err, body, req, res) {
client.use('/avatars/eg.jpg').post(file, function (err, body, req, res) {
client.use('/avatars/eg.jpg').pipe(out).get(function (err) {
var same = fs.readFileSync(__dirname + '/support/eg.jpg').toString('base64') === fs.readFileSync(__dirname + '/support/out-eg.jpg').toString('base64');
expect(same).to.equal(true);

View File

@@ -24,17 +24,18 @@ describe('Users', function(){
})
describe('PUT /users/:id', function(){
it('should update the user', function(done) {
data.users[0].username = 'foobar';
users.use('/' + data.users[0]._id).put(data.users[0], function (err) {
it('should update the user and still be able login', function(done) {
users.use('/' + data.users[0]._id).put({username: 'foobar'}, function (err) {
users.use('/' + data.users[0]._id).get(function (err, user) {
expect(user.email).to.eql(data.users[0].email);
expect(user.password).to.not.exist;
expect(user.username).to.equal('foobar');
done(err);
// should still login
users.use('/login').post({email: data.users[0].email, password: data.users[0].password}, function (err, session, req, res) {
done(err);
});
})
})
})
})