Skip to content

Commit

Permalink
Edit and update feature has been added
Browse files Browse the repository at this point in the history
  • Loading branch information
NIKHIL-PALL committed Apr 13, 2024
1 parent 07937ad commit 48ab867
Show file tree
Hide file tree
Showing 25 changed files with 762 additions and 74 deletions.
3 changes: 3 additions & 0 deletions backend/app.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const cors = require("cors");
const app = express();
const User = require("./model/User");
const UserRoutes = require("./routes/UserRoutes");
const BlogRoutes = require("./routes/BlogRoutes")

dotenv.config();
app.use(cors());
app.use(express.json())
app.use("/api/user", UserRoutes);
app.use("/api/blog", BlogRoutes);
Expand Down
32 changes: 25 additions & 7 deletions backend/contollers/BlogsController.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,22 @@ const getAllBlogs = async(req, res) => {
res.status(200).json(allBlogs)
}

const getBlogsByUserId = async(req, res) => {
const {uid} = req.params;
try{
const user = await User.findById(uid).populate('blogs');
if(!user) {
return res.status(404).json({message : "Unable to find the User"});
}
const blogs = user.blogs;

return res.status(200).json(blogs);

}
catch(err) {
res.status(500).json({message : err.message});
}
}
const getBlogById = async(req, res) => {
const {bid} = req.params;
try{
Expand All @@ -22,15 +38,15 @@ const getBlogById = async(req, res) => {
}

const createBlog = async (req, res) => {
const { title, content, creator } = req.body;
const { title, content, creator, author, date } = req.body;

try {
const user = await User.findById(creator);
if (!user) {
return res.status(404).json({ message: "User not found" });
}

const newBlog = new Blog({ title, content, creator });
const newBlog = new Blog({ title, content, creator , author, date});
await newBlog.save();

user.blogs.push(newBlog);
Expand All @@ -48,20 +64,21 @@ const updateBlog = async(req, res) => {

const {bid} = req.params;
const data = await Blog.findById(bid);
if(creator !== data.creator) {
console.log(data);
if(creator != data.creator) {
return res.status(401).json({message : "Unauthorized"});
}
const blog = {
title,
blog
content
}
try{

const updatedBlog = await Blog.findByIdAndUpdate(bid, blog, {new : true});
if(!updateBlog) {
if(!updatedBlog) {
return res.status(402).json({message : "no blog found"});
}
res.status(200).json(updateBlog);
res.status(200).json(updatedBlog);
}
catch(err) {
res.status(500).json({message : " Unable to update"});
Expand Down Expand Up @@ -96,5 +113,6 @@ const deleteBlog = async (req, res) => {
deleteBlog,
createBlog,
updateBlog,
getBlogById
getBlogById,
getBlogsByUserId
}
14 changes: 11 additions & 3 deletions backend/contollers/UserController.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ const getUserById = async(req, res) => {
}
const login = async (req, res) => {
const { email, password } = req.body;

if(!email) return res.status(409).json({message : "Email is required."});
if(!password) return res.status(409).json({message : "Password is required"});
try {
const existingUser = await User.findOne({ email });
if (!existingUser) {
Expand All @@ -34,7 +35,7 @@ const login = async (req, res) => {
.json({ message: "No existing user found. Try Signing up instead" });
}
if (password === existingUser.password) {
return res.status(200).json({ message: "Logged in successfully" });
return res.status(200).json(existingUser);
} else {
return res.status(401).json({ message: "Incorrect password" });
}
Expand All @@ -46,6 +47,13 @@ const login = async (req, res) => {

const signup = async (req, res) => {
const { name, email, password } = req.body;
if(!name || !email || !password) {
return res.status(409).json({message : "Please fill all the details."});
}
if(!email.includes("@")) return res.status(409).json({message : "Please enter a valid email"});

if(password.length < 6) return res.status(409).json({message : "Password must contain atleast 6 letters."})


try {
let existingUser = await User.findOne({ email });
Expand All @@ -54,7 +62,7 @@ const signup = async (req, res) => {
.status(409)
.json({ message: "User already exists. Please try login instead" });
}

const newUser = new User({ name, email, password });
await newUser.save();

Expand Down
2 changes: 2 additions & 0 deletions backend/model/Blogs.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const BlogSchema = new mongoose.Schema({
content : {type : String, required : true},
image : {type : String},
creator : {type : mongoose.Types.ObjectId, required : true, ref : 'User'},
author : {type : String},
date : {type : String}

}, {timestamps : true})

Expand Down
1 change: 1 addition & 0 deletions backend/routes/BlogRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const router = express.Router();


router.get("/blogs", BlogsController.getAllBlogs);
router.get("/myblogs/:uid", BlogsController.getBlogsByUserId)
router.post("/create",BlogsController.createBlog);
router.get("/:bid", BlogsController.getBlogById);
router.patch("/:bid", BlogsController.updateBlog);
Expand Down
39 changes: 39 additions & 0 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.3",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Expand Down
2 changes: 1 addition & 1 deletion frontend/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blog</title>
</head>
<body>
<body class="min-h-screen">
<div id="root"></div>
</body>
</html>
46 changes: 38 additions & 8 deletions frontend/src/App.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,47 @@
import Navbar from "./components/Navbar";
import Hero from "./components/Hero";
import React from "react";

import "./App.css";
import "./index.css"
import Blog from "./components/Blog";

import React, { useState } from "react";
import { BrowserRouter, Routes, Route } from 'react-router-dom';

import AuthContext from './Contexts/AuthContext';


import NewBlog from './components/pages/NewBlog';
import Navbar from "./components/Navbar";
import Home from "./components/pages/Home"
import Auth from './components/pages/Auth';
import MyBlogs from './components/pages/MyBlogs';
import EditBlog from "./components/pages/EditBlog";


function App() {
const [isLoggedIn , setIsLoggedIn] = useState(false);
const [userId, setUserId ] = useState(null);
const login = (userId) => {
setIsLoggedIn(true);
setUserId(userId);
}

const logout = () => {
setIsLoggedIn(false);
setUserId(null);
}

return (
<React.Fragment>
<Navbar />
<Hero />
<Blog />
<BrowserRouter>
<Navbar />
<AuthContext.Provider value={{isLoggedIn : isLoggedIn,login : login, logout : logout , userId : userId}}>
<Routes>
<Route path='/' exact Component={Home}/>
<Route path="/blog" exact Component={Auth}/>
<Route path='/myblogs' exact Component={MyBlogs}/>
<Route path="/create" exact Component={NewBlog}/>
<Route path='/edit/:bid' exact Component={EditBlog}/>
</Routes>
</AuthContext.Provider>
</BrowserRouter>
</React.Fragment>
);
}
Expand Down
14 changes: 14 additions & 0 deletions frontend/src/Contexts/AuthContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@


import {createContext} from "react";

const AuthContext = createContext({
userId : null,
isLoggedIn : false,

login : () => {},
logout : () => {}
})

export default AuthContext;

36 changes: 36 additions & 0 deletions frontend/src/Utils/ConfirmationModal.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@


import React from "react";

const ConfirmationModal = ({ isOpen, title, message, onConfirm, onCancel }) => {
if (!isOpen) {
return null;
}

return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-gray-900 bg-opacity-50">
<div className="bg-white w-1/3 p-6 rounded shadow-lg">
<div className="mb-4">
<h2 className="text-lg font-bold">{title}</h2>
<p className="text-gray-700">{message}</p>
</div>
<div className="flex justify-end">
<button
className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 mr-2 rounded focus:outline-none focus:shadow-outline"
onClick={onConfirm}
>
Confirm
</button>
<button
className="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
onClick={onCancel}
>
Cancel
</button>
</div>
</div>
</div>
);
};

export default ConfirmationModal;
17 changes: 17 additions & 0 deletions frontend/src/Utils/ErrorModal.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React from 'react';

const ErrorModal = ({ isOpen, message, onClose }) => {
return isOpen ? (
<div className="fixed inset-0 flex items-center justify-center">
<div className="fixed inset-0 bg-gray-900 opacity-50"></div>
<div className="bg-white p-2 rounded-lg z-10 flex flex-col ">
<span className=" self-end cursor-pointer text-5xl" onClick={onClose}>
&times;
</span>
<p className="text-red-600 text-lg">{message}</p>
</div>
</div>
) : null;
};

export default ErrorModal;
21 changes: 21 additions & 0 deletions frontend/src/Utils/date-formatter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@



const getDate = () => {
const currentDate = new Date();

const options = {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: true // Use AM/PM format
};

const formattedDateTime = currentDate.toLocaleString('en-GB', options); // 'en-GB' represents the format dd-mm-yyyy
console.log(formattedDateTime); // Output: 11-04-2024, 05:03 PM
return formattedDateTime;
}

export default getDate;
Loading

0 comments on commit 48ab867

Please sign in to comment.