Skip to content

Commit

Permalink
tested all the routes
Browse files Browse the repository at this point in the history
  • Loading branch information
pushkar1713 committed Sep 6, 2024
1 parent f18f7d1 commit 7f83452
Showing 1 changed file with 28 additions and 15 deletions.
43 changes: 28 additions & 15 deletions backend/src/routes/posts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,44 +19,54 @@ postRouter.use("/*", async (c, next) => {
// otherwise we return a 403 status code

const header = c.req.header("authorization") || "";
const token = header.split("")[1];
const [bearer, token] = header.split(" ");

if (!token || bearer !== "Bearer") {
throw new Error("Invalid or missing authorization header");
}

const response = await verify(token, c.env.JWT_SECRET);

if (response) {
//@ts-ignore
c.set("userId", response.id);
next();
await next();
} else {
c.status(403);
return c.json({ error: "unauthorized" });
}
});

postRouter.post("/blog", async (c) => {
postRouter.post("/", async (c) => {
const prisma = getPrisma(c.env.DATABASE_URL);
const body = await c.req.json();
const userId = c.get("userId");

const blog = prisma.post.create({
const blog = await prisma.post.create({
data: {
title: body.title,
content: body.content,
author_id: userId,
},
});

return c.text("blog route");
return c.json({ id: blog.id });
});

postRouter.get("/bulk", async (c) => {
const prisma = getPrisma(c.env.DATABASE_URL);
const blogs = await prisma.post.findMany();
return c.json(blogs);
});

postRouter.get("/:id", async (c) => {
const prisma = getPrisma(c.env.DATABASE_URL);
const body = await c.req.json();
const id = c.req.param("id");

try {
const blog = prisma.post.findUnique({
const blog = await prisma.post.findUnique({
where: {
id: body.id,
id: id,
},
});

Expand All @@ -74,13 +84,16 @@ postRouter.get("/:id", async (c) => {
postRouter.put("/", async (c) => {
const prisma = getPrisma(c.env.DATABASE_URL);
const body = await c.req.json();
return c.text("this is a put route");
});

postRouter.get("/bulk", async (c) => {
const prisma = getPrisma(c.env.DATABASE_URL);
const blogs = prisma.post.findMany();
return c.json({
blogs,
const updatedBlog = await prisma.post.update({
where: {
id: body.id,
},
data: {
title: body.title,
content: body.content,
},
});

return c.text("blog updated");
});

0 comments on commit 7f83452

Please sign in to comment.