forked from juice-shop/juice-shop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoupon.js
28 lines (27 loc) · 840 Bytes
/
coupon.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const insecurity = require('../lib/insecurity')
const models = require('../models/index')
module.exports = function applyCoupon () {
return ({ params }, res, next) => {
const id = params.id
let coupon = params.coupon ? decodeURIComponent(params.coupon) : undefined
const discount = insecurity.discountFromCoupon(coupon)
coupon = discount ? coupon : null
models.Basket.findByPk(id).then(basket => {
if (basket) {
basket.update({ coupon }).then(() => {
if (discount) {
res.json({ discount })
} else {
res.status(404).send('Invalid coupon.')
}
}).catch(error => {
next(error)
})
} else {
next(new Error('Basket with id=' + id + ' does not exist.'))
}
}).catch(error => {
next(error)
})
}
}