Skip to content

Commit

Permalink
refactor: route.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
ogatalars authored Mar 3, 2024
1 parent f71d396 commit fe176bc
Showing 1 changed file with 20 additions and 17 deletions.
37 changes: 20 additions & 17 deletions src/app/api/users/route.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,30 @@
import { user } from "@/dao/user.dao";
import { NextApiRequest } from "next";
import { NextResponse } from "next/server";
import { NextResponse, NextRequest } from "next/server";
import { z } from "zod";

export async function GET(req: NextApiRequest) {
try {
const { username, email, page, pageSize } = req.query || {};
const checkGetAllUsersParams = z.object({
username: z.string().optional(),
email: z.string().optional(),
page: z.number().optional().transform((val) => (val ? Number(val) : undefined)),
pageSize: z.number().optional().transform((val) => (val ? Number(val) : undefined)),
});

const filter = {
username: typeof username === "string" ? username : undefined,
email: typeof email === "string" ? email : undefined,
};
export async function GET(req: NextRequest) {
try {

const queryParams = checkGetAllUsersParams.parse(Object.fromEntries(req.nextUrl.searchParams));

const pageNum = page ? parseInt(page as string, 10) : 1;
const size = pageSize ? parseInt(pageSize as string, 10) : 10;
const { username, email, page, pageSize } = queryParams;

const users = await user.fetchUsers({ username, email }, page, pageSize);

const users = await user.fetchUsers(filter, pageNum, size);
return new NextResponse(JSON.stringify(users), {
status: 201,
status: 200,
});
} catch (error) {
return new NextResponse(
JSON.stringify({ error: "Internal Server Error" }),
{ status: 500 }
);
console.error(error);
return new NextResponse(JSON.stringify({ error: "Internal Server Error" }), {
status: 500,
});
}
}

0 comments on commit fe176bc

Please sign in to comment.