SHARE
TWEET

TUTORIAL#8 SERVER

Pedophilicus_gonicus Nov 19th, 2019 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //Create express app
  2. const express = require('express');
  3. let app = express();
  4.  
  5. //Database variables
  6. let mongo = require('mongodb');
  7. let MongoClient = mongo.MongoClient;
  8. let db;
  9. //View engine
  10. app.set("view engine", "pug");
  11.  
  12. //Set up the routes
  13. app.use(express.static("views"));
  14. app.get("/", sendIndex);
  15. app.get("/cards/:cardID", sendCard);
  16. app.post("/cards",parseCards);
  17.  
  18. function sendIndex(req, res, next){
  19.     db.collection("cards").distinct("cardClass",function(err1,value1){
  20.         db.collection("cards").distinct("rarity",function(err2,value2){
  21.             if(err1) throw err1;
  22.             if(err2) throw err2;
  23.             res.render("index",{cardClasses: value1, rarity: value2});
  24.         });
  25.     });
  26. }
  27.  
  28. function sendCard(req, res, next){
  29.     let oid;
  30.     try{
  31.         oid = new mongo.ObjectID(req.params.cardID);
  32.     }catch{
  33.         res.status(404).send("Unknown ID");
  34.         return;
  35.     }
  36.    
  37.     db.collection("cards").findOne({"_id":oid}, function(err, result){
  38.         if(err){
  39.             res.status(500).send("Error reading database.");
  40.             return;
  41.         }
  42.         if(!result){
  43.             res.status(404).send("Unknown ID");
  44.             return;
  45.         }
  46.         res.status(200);
  47.         res.format({
  48.             "text/html": () => {res.render("card", result);},
  49.             "application/json": () => {res.send(cards[cardID]);}
  50.         });
  51.     });
  52. }
  53.  
  54. function parseCards(req,res,next){
  55.     console.log("PARSING REQUEST");
  56.     db.collection("cards").find(req.query).toArray(function(err,result){
  57.         if(err){res.status(500); return;};
  58.         res.send({info: result});
  59.     });
  60. }
  61.  
  62.  
  63. // Initialize database connection
  64. MongoClient.connect("mongodb://localhost:27017/", function(err, client) {
  65.   if(err) throw err;
  66.  
  67.   //Get the t8 database
  68.   db = client.db('t8');
  69.   // Start server once Mongo is initialized
  70.   app.listen(3000);
  71.   console.log("Listening on port 3000");
  72. });
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top