From 2fc76660a194b4e8b8ac5a1e1de44fa7ec7625d1 Mon Sep 17 00:00:00 2001 From: Ashelyn Dawn Date: Sat, 30 Jan 2021 18:16:58 -0700 Subject: [PATCH] Coupons API --- api/coupons.js | 35 +++++++++++++++++++++++++++++++++++ api/index.js | 1 + db/models/coupon.js | 9 +++++++++ 3 files changed, 45 insertions(+) create mode 100644 api/coupons.js diff --git a/api/coupons.js b/api/coupons.js new file mode 100644 index 0000000..8cbb593 --- /dev/null +++ b/api/coupons.js @@ -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) +}) \ No newline at end of file diff --git a/api/index.js b/api/index.js index 3733a79..b4c0a39 100644 --- a/api/index.js +++ b/api/index.js @@ -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') diff --git a/db/models/coupon.js b/db/models/coupon.js index 3732aa6..6309398 100644 --- a/db/models/coupon.js +++ b/db/models/coupon.js @@ -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_') +} \ No newline at end of file