Mern Blog App – API Source Code

Mern Blog App – API Source Code

Share It With Your Firends:

package.json

you can simply use this package.json and run npm i to install all the dependencies.

npm i
{
  "name": "api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.1.0",
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "jsonwebtoken": "^9.0.0",
    "mongoose": "^7.0.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.21"
  }
}

Index.js

import express from "express"
import dotenv from "dotenv"
import cors from "cors"
import "./db/database.js"
import UserRouter from "./routes/user.js"
import BlogRouter from "./routes/blog.js"

dotenv.config()

const port = process.env.PORT
const app = express()

app.use(express.json())
app.use(cors({credentials: true}))

// using routes
app.use("/api/user", UserRouter)
app.use("/api/blog", BlogRouter)


app.listen(port, ()=>{
    console.log("App is running on port: ",port);
})

database.js

import dotenv from "dotenv"
import mongoose from "mongoose"

dotenv.config()

mongoose.connect(process.env.MONGO_URL)
.then(()=>console.log("connected to the database"))
.catch(err=>console.log(err))

BlogSchema.js

import mongoose from "mongoose";

const blogSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    content: {
        type: String,
        required: true
    },
    image: {
        type: String
    },
    user:{
        type: mongoose.Schema.Types.ObjectId,
        ref: "user"
    },
    createdOn: {
        type: Date,
        default: Date.now
    }
})

const Blog = mongoose.model("Blog", blogSchema)

export default Blog;

UserSchema.js

import mongoose from "mongoose"

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password:{
        type: String,
        required: true
    }
})

const User = mongoose.model("User", userSchema)

export default User;

routes:

We are going to use this 2 routes

blog.js

import Blog from "../models/BlogSchema.js";
import express from "express";
import getAuth from "../middleware/auth.js";

const BlogRouter = express.Router()
BlogRouter.use(express.json())

const response = (res, status, result) => {
    res.status(status).json(result);
}

BlogRouter.get("/", async (req, res) => {
    await Blog.find()
        .then(result => {
            response(res, 200, result)
        })
        .catch(err => {
            response(res, 400, { error: err })
        })
})

BlogRouter.post("/create", getAuth, async (req, res) => {
    try {
        const { title, content, image } = req.body
        if (title && content) {
            const blog = new Blog({
                title, content, image, user: req.userId
            })
            await blog.save()
            response(res, 200, { msg: "blog created", blog: blog })
        }
    } catch (error) {
        response(res, 400, { error: error })
    }
})

BlogRouter.delete("/delete", getAuth, async (req, res)=>{
    try {
        const blog = await Blog.findOneAndDelete({user: req.userId, _id: req.body.id})
        if(!blog){
            response(res, 404, {error: "blog not found"})
        }
        response(res, 200, {msg: "blog deleted!"})
    } catch (error) {
        response(res, 400, { error: error })
    }
})

BlogRouter.put("/update", getAuth, async (req, res)=>{
    const {title, content, image, id} = req.body;
    await Blog.findOneAndUpdate({user: req.userId, _id: id}, {
        title, content, image
    })
    .then((result)=>response(res, 200, {msg: "blog updated", blog: result}))
    .catch(err=>response(res, 400, err))
})



export default BlogRouter;

user.js

import express from "express"
import User from "../models/UserSchema.js"
import jwt from "jsonwebtoken"
import bcrypt from "bcrypt"

const UserRouter = express.Router()
UserRouter.use(express.json())

UserRouter.get("/", async (req, res)=>{
    await User.find()
    .then((result)=>{
        res.status(200).json(result)
    })
    .catch(err=>{
        res.status(400).json({error: err})
    })
})

UserRouter.post("/register", async (req, res)=>{
    try {
        const {name, email, password} = req.body;
        if(name && email && password){
            const hashPassword = await bcrypt.hash(password, 10)
            const user = await User.create({name, email, password: hashPassword})
            res.status(200).json({msg: "user registered successfully", user: user})
        }else{
            res.status(400).json({msg: "please fill the required fields"})
        }
    } catch (error) {
        res.status(400).json({error: error})
    }
})

UserRouter.post("/login", async (req, res)=>{
    try {
        const {email, password} = req.body;
        const existUser = await User.findOne({email})
        if(!existUser){
            res.status(404).json({error: "user not found"})
        }
        const comparePassword = await bcrypt.compare(password, existUser.password)
        if(!comparePassword){
            res.status(400).json({msg: "Wrong Credentials"})
        }
        const token = jwt.sign({id: existUser._id}, process.env.SECRET)
        res.status(201).json({msg: "user logged in", token: token})
    } catch (error) {
        res.status(400).json({error: error})
    }
})

export default UserRouter;

middleware

this is the code for the middleware

auth.js

import User from "../models/UserSchema.js";
import jwt from "jsonwebtoken";
import dotenv from "dotenv"

dotenv.config()

const getAuth = async (req, res, next) => {
    try {
        const token = req.headers.token;
        if(!token){
            res.status(401).json({error: "unauthorized"})
        }

        const verifyToken = jwt.verify(token, process.env.SECRET)
        // console.log(verifyToken);
        const auth = await User.findById(verifyToken.id)

        req.userId = verifyToken.id
        req.auth = auth
        next()
    } catch (error) {
        res.status(401).json({error: "unauthorized"})
    }
}

export default getAuth;

Share It With Your Friends

1 Comment

Leave a Reply

Recent Posts

  • All Post
  • A.I.
  • AI
  • c
  • c++
  • computer
  • cryptocurrency
  • database
  • digital marketing
  • finance
  • hacking
  • HTML
  • java
  • Marketing
  • network
  • other
  • programming
  • python
  • react
  • social
  • Tools
  • Uncategorized
  • web devlopment
    •   Back
    • drawing In Python
DIY AI Voice Assistant In Python

September 8, 2023

Build your own AI assistant with Python! Learn to recognize voice commands, generate responses, and more. Create your virtual companion…

share it

Recent Posts

  • All Post
  • A.I.
  • AI
  • c
  • c++
  • computer
  • cryptocurrency
  • database
  • digital marketing
  • finance
  • hacking
  • HTML
  • java
  • Marketing
  • network
  • other
  • programming
  • python
  • react
  • social
  • Tools
  • Uncategorized
  • web devlopment
    •   Back
    • drawing In Python

Additional Content

CodeWithAM

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus luctus.

Products

Automated Chatbot

Data Security

Virtual Reality

Communication

Support

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Codewitham