Guest User

Untitled

a guest
Dec 15th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. //include the model (aka DB connection)
  2. var db = require('../models/dbconnection');
  3.  
  4. //create class
  5. var Strain = {
  6. //function to query all items
  7. getAllItems: function (req, res) {
  8. //grab the site section from the req variable (/strains/)
  9. //console.log(req) to see all the goodies
  10. let pathname = req._parsedUrl.pathname.split('/');
  11. //split makes an array, so pick the second row
  12. let section = pathname[1];
  13.  
  14. //query the DB using prepared statement
  15. var results = db.query('SELECT * from ??', [section], function (error, results, fields) {
  16. //if error, print blank results
  17. if (error) {
  18. // console.log(error);
  19. var apiResult = {};
  20.  
  21. apiResult.meta = {
  22. table: section,
  23. type: "collection",
  24. total: 0
  25. }
  26. //create an empty data table
  27. apiResult.data = [];
  28.  
  29. //send the results (apiResult) as JSON to Express (res)
  30. //Express uses res.json() to send JSON to client
  31. //you will see res.send() used for HTML
  32. res.json(apiResult);
  33.  
  34. }
  35.  
  36. //make results
  37. var resultJson = JSON.stringify(results);
  38. resultJson = JSON.parse(resultJson);
  39. var apiResult = {};
  40.  
  41.  
  42. // create a meta table to help apps
  43. //do we have results? what section? etc
  44. apiResult.meta = {
  45. table: section,
  46. type: "collection",
  47. total: 1,
  48. total_entries: 0
  49. }
  50.  
  51. //add our JSON results to the data table
  52. apiResult.data = resultJson;
  53.  
  54. //send JSON to Express
  55. res.json(apiResult);
  56. });
  57. },
  58. };
  59. module.exports = Strain;
Add Comment
Please, Sign In to add comment