Improve merge on update

This commit is contained in:
John Lyon-Smith
2018-05-09 15:32:53 -07:00
parent 57355088f0
commit d087da2ce7
8 changed files with 40 additions and 58 deletions

View File

@@ -183,30 +183,24 @@ export class UserRoutes {
throw createError.Forbidden()
}
const User = this.db.User
let userUpdates = null
try {
userUpdates = new User(req.body)
} catch (err) {
throw createError.BadRequest("Invalid data")
}
if (isSelf && !isAdmin) {
throw createError.BadRequest("Cannot modify own administrator level")
}
const foundUser = await User.findById(userUpdates._id)
const User = this.db.User
const user = await User.findById(req.body._id)
if (!foundUser) {
throw createError.NotFound(`User with _id ${user._id} was not found`)
if (!user) {
throw createError.NotFound(`User with _id ${req.body._id} was not found`)
}
// We don't allow direct updates to the email field so remove it if present
const userUpdates = new User(req.body)
delete userUpdates.email
foundUser.merge(userUpdates)
const savedUser = await foundUser.save()
user.merge(userUpdates)
const savedUser = await user.save()
res.json(savedUser.toClient(req.user))
}