Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Create express app
- const express = require('express');
- let app = express();
- //Database variables
- let mongo = require('mongodb');
- let MongoClient = mongo.MongoClient;
- let db;
- //View engine
- app.set("view engine", "pug");
- //Set up the routes
- app.use(express.static("views"));
- app.get("/", sendIndex);
- app.get("/cards/:cardID", sendCard);
- app.post("/cards",parseCards);
- function sendIndex(req, res, next){
- db.collection("cards").distinct("cardClass",function(err1,value1){
- db.collection("cards").distinct("rarity",function(err2,value2){
- if(err1) throw err1;
- if(err2) throw err2;
- res.render("index",{cardClasses: value1, rarity: value2});
- });
- });
- }
- function sendCard(req, res, next){
- let oid;
- try{
- oid = new mongo.ObjectID(req.params.cardID);
- }catch{
- res.status(404).send("Unknown ID");
- return;
- }
- db.collection("cards").findOne({"_id":oid}, function(err, result){
- if(err){
- res.status(500).send("Error reading database.");
- return;
- }
- if(!result){
- res.status(404).send("Unknown ID");
- return;
- }
- res.status(200);
- res.format({
- "text/html": () => {res.render("card", result);},
- "application/json": () => {res.send(cards[cardID]);}
- });
- });
- }
- function parseCards(req,res,next){
- console.log("PARSING REQUEST");
- db.collection("cards").find(req.query).toArray(function(err,result){
- if(err){res.status(500); return;};
- res.send({info: result});
- });
- }
- // Initialize database connection
- MongoClient.connect("mongodb://localhost:27017/", function(err, client) {
- if(err) throw err;
- //Get the t8 database
- db = client.db('t8');
- // Start server once Mongo is initialized
- app.listen(3000);
- console.log("Listening on port 3000");
- });
Add Comment
Please, Sign In to add comment