Coupons API

main
Ashelyn Dawn 4 years ago
parent 208c938d94
commit 2fc76660a1

@ -0,0 +1,35 @@
const router = module.exports = require('express-promise-router')()
const parseJSON = require('body-parser').json()
const db = require('../db')
const ensureAdmin = require('./middleware/ensureAdmin')
function makeCode(length){
var text = "";
var possible = "ABCDEFGHJKMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
for( var i=0; i < length; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
router.post('/', ensureAdmin, parseJSON, async (req, res) => {
const code = req.body.code || makeCode(10)
const coupon = await db.coupon.create(
code,
req.body.valid_until,
req.body.free_shipping,
req.body.number_allowed_uses,
req.body.flat_discount_cents || 0,
req.body.percent_discount || 0,
req.body.per_sock_discount || 0,
req.body.number_of_socks_free || 0
)
res.json(coupon)
})
router.get('/', ensureAdmin, async (req, res) => {
const coupons = await db.coupon.findAll()
res.json(coupons)
})

@ -25,6 +25,7 @@ router.use('/categories/', require('./categories'))
router.use('/orders/', require('./orders'))
router.use('/shipments/', require('./shipments'))
router.use('/email/', require('./email'))
router.use('/coupons/', require('./coupons'))
router.use((req, res, next)=>{
const err = new Error('Not found')

@ -39,3 +39,12 @@ coupon.find = async function(code){
const {rows} = await pg.query(query);
return joinjs.map(rows, mappings, 'couponMap', 'coupon_')[0]
}
coupon.findAll = async function() {
const query = 'select * from sos.coupon'
debug(query)
const {rows} = await pg.query(query);
return joinjs.map(rows, mappings, 'couponMap', 'coupon_')
}
Loading…
Cancel
Save