Refactoring product route

master
Mark Moffat 2019-11-09 13:29:20 +10:30
parent 87a722d03e
commit b41461c8a3
2 changed files with 49 additions and 1 deletions

View File

@ -25,7 +25,7 @@ router.get('/admin/products', restrict, async (req, res, next) => {
});
});
router.get('/admin/products/filter/:search', async (req, res, next) => {
router.get('/admin/products/filter/:search', restrict, async (req, res, next) => {
const db = req.app.db;
const searchTerm = req.params.search;
const productsIndex = req.app.productsIndex;
@ -37,6 +37,12 @@ router.get('/admin/products/filter/:search', async (req, res, next) => {
// we search on the lunr indexes
const results = await db.products.find({ _id: { $in: lunrIdArray } }).toArray();
if(req.apiAuthenticated){
res.status(200).json(results);
return;
}
res.render('products', {
title: 'Results',
results: results,
@ -205,6 +211,11 @@ router.get('/admin/product/edit/:id', restrict, checkAccess, async (req, res) =>
const images = await common.getImages(req.params.id, req, res);
const product = await db.products.findOne({ _id: common.getId(req.params.id) });
if(!product){
// If API request, return json
if(req.apiAuthenticated){
res.status(400).json({ message: 'Product not found' });
return;
}
req.session.message = 'Product not found';
req.session.messageType = 'danger';
res.redirect('/admin/products');
@ -215,6 +226,12 @@ router.get('/admin/product/edit/:id', restrict, checkAccess, async (req, res) =>
options = product.productOptions;
}
// If API request, return json
if(req.apiAuthenticated){
res.status(200).json(product);
return;
}
res.render('product_edit', {
title: 'Edit product',
result: product,

View File

@ -134,6 +134,37 @@ test('[Success] Search products', async t => {
t.deepEqual(res.body.length, 2);
});
test('[Success] Filter products', async t => {
const res = await g.request
.get('/admin/products/filter/backpack')
.set('apiKey', g.users[0].apiKey)
.expect(200);
// Should be two backpack products
t.deepEqual(res.body.length, 2);
});
test('[Success] Edit a product', async t => {
const res = await g.request
.get(`/admin/product/edit/${g.products[0]._id}`)
.set('apiKey', g.users[0].apiKey)
.expect(200);
// Products should match
t.deepEqual(res.body._id.toString(), g.products[0]._id.toString());
t.deepEqual(res.body.productPermalink, g.products[0].productPermalink);
});
test('[Fail] Edit an invalid product', async t => {
const res = await g.request
.get('/admin/product/edit/some_invalid_product')
.set('apiKey', g.users[0].apiKey)
.expect(400);
// Check the returned message
t.deepEqual(res.body.message, 'Product not found');
});
test('[Success] Add a product', async t => {
const product = {
productPermalink: 'test-jacket',