Commit 57b41d8d authored by Poojasri's avatar Poojasri
Browse files

getbyid and update

parent a5fa53fa
Loading
Loading
Loading
Loading
+70 −1
Original line number Diff line number Diff line
@@ -61,3 +61,72 @@ export const getAllUsers = async (c: Context) => {
    return c.json({ error: error.message }, 500);
  }
};

export const getUserById = async (c: Context) => {
  try {
    const id = Number(c.req.param("id")); 
    if (isNaN(id)) {
      return c.json({ error: "Invalid ID format" }, 400);
    }

    const user = await db
      .select({
        id: users.id,
        firstName: users.firstName,
        lastName: users.lastName,
        phoneNumber: users.phoneNumber,
        email: users.email,
      })
      .from(users)
      .where(eq(users.id, id)); 

    if (!user.length) {
      return c.json({ error: "User not found" }, 404);
    }

    return c.json(user[0], 200);
  } catch (error: any) {
    return c.json({ error: error.message }, 500);
  }
};

export const updateUser = async (c: Context) => {
  try {
    const id = Number(c.req.param("id")); 

    if (isNaN(id)) {
      return c.json({ error: "Invalid ID format" }, 400);
    }

    const body = await c.req.json();

    const existingUser = await db
      .select()
      .from(users)
      .where(eq(users.id, id)); 

    if (!existingUser.length) {
      return c.json({ error: "User not found" }, 404);
    }

    const updatedData = {
      firstName: body.firstName?.trim() ,
      lastName: body.lastName?.trim(),
      email: body.email?.trim(),
      phoneNumber: body.phoneNumber,
      updatedAt: new Date(),
    };

    const [updatedUser]: any = await db
      .update(users)
      .set(updatedData)
      .where(eq(users.id, id)) 
      .returning();

    return c.json(updatedUser, 200);
  } catch (error: any) {
    return c.json({ error: error.message }, 500);
  }
};

+19 −1
Original line number Diff line number Diff line
import { Hono } from "hono";
import { createUser, getAllUsers } from "../user/user.controller";
import { createUser, getAllUsers, getUserById , updateUser} from "../user/user.controller";

export const userRoutes = (app: Hono) => {
  app.post("/user/create", async (c) => {
@@ -21,4 +21,22 @@ export const userRoutes = (app: Hono) => {

    return getAllUsers(c);
  });

  app.get("/user/getbyid/:id", async (c) => {
    try {
    } catch (error: any) {
      return c.json({ error: error.errors }, 400);
    }

    return getUserById(c);
  });

  app.put("/user/update/:id", async (c) => {
    try {
    } catch (error: any) {
      return c.json({ error: error.errors }, 400);
    }

    return updateUser(c);
  });
};