const express=require(“express”);
const bodyParser=require(“body-parser”);
const methodOverride=require(“method-override”);
const expressSanitizer=require(“express-sanitizer”);
const app=express();
const mongoose=require(“mongoose”);
mongoose.connect(“mongodb://localhost/Blogger”,{useNewUrlParser:true,useUnifiedTopology:true});
app.use(express.static(“public”));
app.use(bodyParser.urlencoded({extended:true}));
app.set(“view engine”, “ejs”);
//Schema Setup
var blogSchema=new mongoose.Schema({
title:String,
image:String,
body:String,
category:String,
created:{type:Date,default:Date.now}
});
var Blog=mongoose.model(“Blog”, blogSchema);
//Home Route
app.get("/",function(req,res){
res.render(“landing”);
});
//Index Route
app.get("/categories",function(req,res){
res.render(“categories”);
});
app.get("/categories/technical",function(req,res){
res.render(“technical”);
});
app.get("/categories/other",function(req,res){
res.render(“other”);
});
app.get("/contact",function(req,res){
res.render(“contact”);
});
//category wise routes:
//Technical routes
//Algorithm
app.get("/categories/technical/algorithms",function(req,res){
Blog.find({},function(err,blogs){
if(err)
{
console.log(err);
}
else
{
res.render("/algorithms/algo",{blogs: blogs});
}
});
app.get("/categories/technical/algorithms/new",function(req,res){
res.render(“algorithms/newalgo”);
});
//create Algorithm
app.post("/categories/technical/algorithms",function(req,res){
req.body.blog.body=req.sanitize(req.body.blog.body)
console.log("===============");
console.log(req.body);
Blog.create(req.body.blog,function(err,newBlog){
if(err){
res.render("/algorithms/newalgo");
}
else{
res.redirect("/categories/technical/algorithms");
}
});
});
//show route Algorithm
app.get("/categories/technical/algorithms:id",function(req,res){
Blog.findById(req.params.id,function(err,foundBlog){
if(err)
{
res.redirect("/categories/technical/algorithms");
}
else
{
res.render("/algorithms/showalgo",{blog:foundBlog})
}
});
});
//Edit Route Algorithm
app.get("/categories/technical/algorithms/:id/edit",function(req,res){
Blog.findById(req.params.id,function(err,foundBlog){
if(err){
res.redirect("/categories/technical/algorithms");
}
else{
res.render("/algorithms/editalgo", {blog: foundBlog});
}
});
});
//Update route Algorithm
app.put("/categories/technical/algorithms/:id",function(req,res){
req.body.blog.body=req.sanitize(req.body.blog.body);
Blog.findByIdAndUpdate(req.params.id,req.body.blog,function(err,updatedBlog){
if(err)
{
res.redirect("/categories/technical/algorithms");
}
else
{
res.redirect("/categories/technical/algorithms/"+req.params.id);
}
});
});
app.listen(4000,function(){
console.log(“server running on port 4000”);
});