Skip to content

Commit

Permalink
added validations routes and controller model logic and tested all en…
Browse files Browse the repository at this point in the history
…dpoints with postman
  • Loading branch information
ikumar200 committed Jan 15, 2025
1 parent d2c023d commit db1d53d
Show file tree
Hide file tree
Showing 19 changed files with 939 additions and 32 deletions.
671 changes: 660 additions & 11 deletions backend/package-lock.json

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,22 @@
"license": "ISC",
"description": "",
"devDependencies": {
"@types/bcrypt": "^5.0.2",
"@types/cors": "^2.8.17",
"@types/dotenv": "^6.1.1",
"@types/express": "^5.0.0",
"@types/jsonwebtoken": "^9.0.7",
"prisma": "^6.2.1",
"ts-node-dev": "^2.0.0",
"typescript": "^5.7.3"
},
"dependencies": {
"@prisma/client": "^6.2.1",
"bcrypt": "^5.1.1",
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"jsonwebtoken": "^9.0.2",
"zod": "^3.24.1"
}
}
23 changes: 23 additions & 0 deletions backend/prisma/migrations/20250114114806_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
-- CreateTable
CREATE TABLE "User" (
"id" SERIAL NOT NULL,
"email" TEXT NOT NULL,
"name" TEXT,

CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "Post" (
"id" SERIAL NOT NULL,
"title" VARCHAR(255) NOT NULL,
"authorId" INTEGER NOT NULL,

CONSTRAINT "Post_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");

-- AddForeignKey
ALTER TABLE "Post" ADD CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
Warnings:
- Added the required column `password` to the `User` table without a default value. This is not possible if the table is not empty.
- Made the column `name` on table `User` required. This step will fail if there are existing NULL values in that column.
*/
-- AlterTable
ALTER TABLE "User" ADD COLUMN "password" TEXT NOT NULL,
ALTER COLUMN "name" SET NOT NULL;
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:
- Added the required column `body` to the `Post` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "Post" ADD COLUMN "body" TEXT NOT NULL;
3 changes: 3 additions & 0 deletions backend/prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
14 changes: 14 additions & 0 deletions backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,18 @@ datasource db {
url = env("DATABASE_URL")
}

model User{
id Int @id @default(autoincrement())
email String @unique
name String
password String
posts Post[]
}

model Post{
id Int @id @default(autoincrement())
title String @db.VarChar(255)
body String
authorId Int
author User @relation(fields: [authorId], references: [id])
}
14 changes: 14 additions & 0 deletions backend/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import express, { Application } from "express";
import postRoutes from "./routes/postRoutes";
import userRoutes from "./routes/userRoutes";

const app: Application = express();

// Middleware
app.use(express.json());

// Routes
app.use("/posts", postRoutes);
app.use("/users", userRoutes);

export default app;
52 changes: 52 additions & 0 deletions backend/src/controllers/postControllers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Request, Response} from "express";
import { createPost,getPostById,getAllPosts } from "../models/postModel";

// export const getPost=async(
// req:Request<{ id: string }>,
// res:Response):Promise<void>=>{

// const {id}=req.params;
// try{
// const post=await getPostById(Number(id));
// if(!post){
// res.status(404).json({msg:"not found"});
// return;
// }
// res.json(post);
// }catch(err){
// res.status(500).json({msg:err});
// }
// };
export const getPost = async (req: Request<{id:string}>, res: Response):Promise<void> => {
const { id } = req.params;
try {
const post = await getPostById(Number(id));
if (!post){
res.status(404).json({ message: "Post not found" });
return }
res.json(post);
} catch (error) {
res.status(500).json({ message: error});
}
};

// Get all posts
export const getPosts = async (req: Request, res: Response) => {
try {
const posts = await getAllPosts();
res.json(posts);
} catch (error) {
res.status(500).json({ message: error });
}
};


export const addPost=async(req: Request, res: Response)=>{
const {title,body,authorId}=req.body;
try{
const post =await createPost({title,body,authorId});
res.status(200).json(post);
}catch(err){
res.status(500).json({ message: err });
}
}
34 changes: 34 additions & 0 deletions backend/src/controllers/userControllers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Request,Response } from "express";
import { createUser,getUserById,getAllUsers } from "../models/userModel";

export const getUser=async(req:Request<{id:string}>,res:Response):Promise<void>=>{
const {id}=req.params;
try{
const user=await getUserById(Number(id));
if(!user){
res.sendStatus(404).json({msg:"User not found"});
return }
res.json(user);
}catch(err){
res.status(500).json({ message: err});
}
};

export const getUsers=async(req:Request,res:Response)=>{
try{
const users=await getAllUsers();
res.json(users);
}catch(err){
res.sendStatus(500).json({msg:err});
}
};

export const addUser=async(req:Request,res:Response)=>{
const {name,email,password}=req.body;
try{
const user=await createUser({name,email,password});
res.sendStatus(201).json(user);
}catch(err){
res.status(500).json({ message: err });
}
}
17 changes: 5 additions & 12 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
import express from "express";
import cors from "cors"
import { authRoutes } from "./routes/authRoutes";
const app=express();
import app from "./app";

app.use(express.json());
app.use(cors());
const PORT = process.env.PORT || 3000;

app.use("/auth",authRoutes);

const PORT=3000;
app.listen(PORT,()=>{
console.log(`listening on port ${PORT}`);
})
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
21 changes: 21 additions & 0 deletions backend/src/middleware/validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Request,Response,NextFunction } from "express";
import { createPostSchema } from "../validations/postValidation";
import { createUserSchema } from "../validations/userValidation";

export const validatePost=(req:Request,res:Response,next:NextFunction)=>{
try{
createPostSchema.parse(req.body);
next();
}catch(err){
res.status(400).json({msg: err});
}
};

export const validateUser=(req:Request,res:Response,next:NextFunction)=>{
try{
createUserSchema.parse(req.body);
next();
}catch(err){
res.status(400).json({msg:err})
};
};
21 changes: 21 additions & 0 deletions backend/src/models/postModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();


export const createPost=async(data:{title:string; body:string; authorId:number})=>{
return await prisma.post.create({
data,
});
};

export const getPostById=async (id:number)=>{
return await prisma.post.findUnique({
where:{id},
});
};

export const getAllPosts=async()=>{
return await prisma.post.findMany({
include:{author:true}
})
}
19 changes: 19 additions & 0 deletions backend/src/models/userModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { PrismaClient } from "@prisma/client";

const prisma=new PrismaClient();

export const createUser=async (data:{name:string; email:string; password:string})=>{
return await prisma.user.create({
data,
});
};

export const getUserById=async (id:number)=>{
return await prisma.user.findUnique({
where:{id},
});
};

export const getAllUsers=async ()=>{
return await prisma.user.findMany();
}
9 changes: 0 additions & 9 deletions backend/src/routes/authRoutes.ts

This file was deleted.

11 changes: 11 additions & 0 deletions backend/src/routes/postRoutes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {Router} from "express";
import { addPost,getPost,getPosts } from "../controllers/postControllers";
import { validatePost } from "../middleware/validation";

const router=Router();

router.get("/",getPosts);
router.get("/:id",getPost);
router.post("/",validatePost,addPost);

export default router;
11 changes: 11 additions & 0 deletions backend/src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Router } from "express";
import { addUser,getUser,getUsers } from "../controllers/userControllers";
import { validatePost, validateUser } from "../middleware/validation";

const router=Router();

router.get("/",getUsers);
router.get("/:id",getUser);
router.post("/",validateUser,addUser);

export default router;
12 changes: 12 additions & 0 deletions backend/src/validations/postValidation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {z} from "zod";

export const createPostSchema=z.object({
title:z.string().min(1,"title is required"),
body:z.string().min(1,"content is req"),
authorId: z.number(),
})

export const updatePostSchema=z.object({
title:z.string().optional(),
body:z.string().optional(),
});
15 changes: 15 additions & 0 deletions backend/src/validations/userValidation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { z } from "zod";


export const createUserSchema = z.object({
name: z.string().min(1, "Name is required"),
email: z.string().email("Invalid email address"),
password:z.string().min(6,"enter min 6 char")
});


export const updateUserSchema = z.object({
name: z.string().optional(),
email: z.string().email("Invalid email address").optional(),
password:z.string().optional(),
});

0 comments on commit db1d53d

Please sign in to comment.