products.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const express = require('express');
  2. const router = express.Router();
  3. const bodyParser = require('body-parser');
  4. const knex = require('../models/database');
  5. var Constants = require('../helpers/Constants.js');
  6. const paginator = require('../helpers/paginator');
  7. const ProductService = require('../services/ProductService');
  8. const RoutingService = require('../services/RoutingService')(router, 'Products');
  9. router.get('/specific',function(req,res){
  10. temp = req.query.val;
  11. knex('Products').where('name','like','%'+temp+'%').select('*').
  12. then(data => {
  13. res.send(data);
  14. }).catch((err) => {
  15. res.status(500).send({error:true, err: err,message:"something went wrong"});
  16. })
  17. });
  18. router.get('/home',function(req,res){
  19. console.log("req")
  20. temp = req.query.val;
  21. //create random query for home serach
  22. knex('Products').orderByRaw('rand()').select('*').limit(9).
  23. then(data => {
  24. res.send(data);
  25. }).catch((err) => {
  26. res.status(500).send({error:true,message:err});
  27. })
  28. });
  29. // Creates Search URL like the commented underneath
  30. //DONT// router.post('/search/:page(\\d+)/:term', search);
  31. //DONT// router.post('/search/:term', search);
  32. RoutingService.search(10, ProductService.presentProducts);
  33. RoutingService.crud();
  34. //
  35. router.post('/import',function(req,res){
  36. if (req.user.role != Constants.Roles.ADMIN) {
  37. res.sendStatus(403);
  38. return;
  39. }
  40. let items = req.body;
  41. insertOrUpdate(knex, 'Products', items).
  42. then(() => res.sendStatus(200)).
  43. catch((e) => res.send(e));
  44. });
  45. function insertOrUpdate(knex, tableName, data) {
  46. const firstData = data[0] ? data[0] : data;
  47. return knex.raw(knex(tableName).insert(data).toQuery() + " ON DUPLICATE KEY UPDATE " +
  48. Object.getOwnPropertyNames(firstData).map((field) => `${field}=VALUES(${field})`).join(", "));
  49. }
  50. module.exports = router;