codecombat/server/middleware/achievements.coffee

31 lines
1.3 KiB
CoffeeScript
Raw Normal View History

2016-04-11 14:59:51 -04:00
errors = require '../commons/errors'
wrap = require 'co-express'
database = require '../commons/database'
Achievement = require '../models/Achievement'
module.exports =
fetchByRelated: wrap (req, res, next) ->
related = req.query.related
return next() unless related
achievements = yield Achievement.find {related: related}
achievements = (achievement.toObject({req: req}) for achievement in achievements)
res.status(200).send(achievements)
put: wrap (req, res, next) ->
achievement = yield database.getDocFromHandle(req, Achievement)
if not achievement
throw new errors.NotFound('Document not found.')
hasPermission = req.user.isAdmin() or req.user.isArtisan()
unless hasPermission or database.isJustFillingTranslations(req, achievement)
throw new errors.Forbidden('Must be an admin, artisan or submitting translations to edit an achievement')
propsWatching = ['query', 'proportionalTo', 'rewards', 'worth', 'function']
oldCopy = _.pick(achievement.toObject(), propsWatching)
2016-04-11 14:59:51 -04:00
database.assignBody(req, achievement)
newCopy = _.pick(achievement.toObject(), propsWatching)
unless _.isEqual(oldCopy, newCopy)
achievement.set('updated', new Date().toISOString())
2016-04-11 14:59:51 -04:00
database.validateDoc(achievement)
achievement = yield achievement.save()
res.status(200).send(achievement.toObject({req: req}))