Skip to content

Commit

Permalink
refactor: improve update category responses♻️
Browse files Browse the repository at this point in the history
  • Loading branch information
shivamvijaywargi committed Nov 17, 2024
1 parent 6534cb0 commit 909ae6b
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 21 deletions.
49 changes: 34 additions & 15 deletions src/modules/categories/category.handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
getAllCategoriesUserRepository,
getCategoryByIdOrNameRepository,
getCategoryRepository,
updateCategoryByIdAndUserIdRepository,
updateCategoryByIdRepository,
} from "./category.repository";

export const createCategory: AppRouteHandler<TCreateCategoryRoute> = async (
Expand Down Expand Up @@ -184,37 +184,56 @@ export const updateCategory: AppRouteHandler<TUpdateCategoryRoute> = async (
const { categoryId } = c.req.valid("param");
const payload = c.req.valid("json");

let category: TSelectCategorySchema | null = null;
const category = await getCategoryRepository(categoryId);

if (user?.role !== AuthRoles.ADMIN) {
logger.debug("Non admin user can only update their own categories");
if (!category) {
logger.error(`Category with id ${categoryId} not found`);
return c.json(
{
success: false,
message: "Category not found",
},
HTTPStatusCodes.NOT_FOUND,
);
}

category = await updateCategoryByIdAndUserIdRepository(
categoryId,
payload,
user?.id,
if (user?.role !== AuthRoles.ADMIN && category.userId !== user?.id) {
logger.error(
`User ${user?.id} not authorized to update category ${categoryId}`,
);
return c.json(
{
success: false,
message: "You are not authorized to update this category",
},
HTTPStatusCodes.FORBIDDEN,
);
} else if (user?.role === AuthRoles.ADMIN) {
category = await updateCategoryByIdAndUserIdRepository(categoryId, payload);
}

if (!category) {
const updatedCategory = await updateCategoryByIdRepository(
categoryId,
payload,
);

if (!updatedCategory) {
logger.error("Failed to update category");
return c.json(
{
success: false,
message: "Invalid category id or you are not allowed to update",
message: "Failed to update category",
},
HTTPStatusCodes.NOT_FOUND,
HTTPStatusCodes.INTERNAL_SERVER_ERROR,
);
}

logger.info(`Category updated successfully with name ${category.name}`);
logger.info(
`Category updated successfully with name ${updatedCategory.name}`,
);
return c.json(
{
success: true,
message: "Category updated successfully",
data: category,
data: updatedCategory,
},
HTTPStatusCodes.OK,
);
Expand Down
7 changes: 1 addition & 6 deletions src/modules/categories/category.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,17 +193,12 @@ export async function getCategoryByIdOrNameRepository(
return category;
}

export async function updateCategoryByIdAndUserIdRepository(
export async function updateCategoryByIdRepository(
categoryId: string,
categoryPayload: Partial<TInsertCategorySchema>,
userId?: string,
) {
const whereCondition = [eq(categoryModel.id, categoryId)];

if (userId) {
whereCondition.push(eq(categoryModel.userId, userId));
}

categoryPayload.name = categoryPayload?.name?.toLowerCase();
categoryPayload.updatedAt = new Date();

Expand Down
7 changes: 7 additions & 0 deletions src/modules/categories/category.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,13 @@ export const updateCategoryRoute = createRoute({
}),
"You are not allowed to perform this action",
),
[HTTPStatusCodes.INTERNAL_SERVER_ERROR]: jsonContent(
z.object({
success: z.boolean().default(false),
message: z.string(),
}),
"Failed to update category",
),
},
});

Expand Down

0 comments on commit 909ae6b

Please sign in to comment.