|
|
@@ -1,51 +1,67 @@
|
|
|
import {
|
|
|
- Category
|
|
|
+ Category
|
|
|
} from "../../../models/Category";
|
|
|
import {
|
|
|
- Product
|
|
|
+ Product
|
|
|
} from "../../../models/Product";
|
|
|
import {
|
|
|
- DeleteCategoryInput,
|
|
|
- DeleteCategoryResult
|
|
|
+ DeleteCategoryResult,
|
|
|
+ DeleteCategoryInput
|
|
|
} from "./types";
|
|
|
|
|
|
const deleteCategory = async (userID: string, input: DeleteCategoryInput): Promise<DeleteCategoryResult> => {
|
|
|
try {
|
|
|
const {
|
|
|
- categoryID
|
|
|
- } = input;
|
|
|
+ categoryIDs
|
|
|
+ } = input;
|
|
|
|
|
|
- const category = await Category.findOne({
|
|
|
- _id: categoryID,
|
|
|
- userID
|
|
|
- });
|
|
|
- if (!category) {
|
|
|
+ const normalizedCategoryIDs = Array.isArray(categoryIDs)
|
|
|
+ ? categoryIDs
|
|
|
+ : categoryIDs ? [categoryIDs] : [];
|
|
|
+
|
|
|
+ if (normalizedCategoryIDs.length === 0) {
|
|
|
return {
|
|
|
- message: "category-not-found",
|
|
|
- code: 404
|
|
|
+ message: "categoryIDs-cannot-be-empty",
|
|
|
+ code: 400
|
|
|
};
|
|
|
}
|
|
|
|
|
|
const productInCategory = await Product.findOne({
|
|
|
- categoryID
|
|
|
+ categoryIDs: {
|
|
|
+ $in: normalizedCategoryIDs
|
|
|
+ }
|
|
|
});
|
|
|
+
|
|
|
if (productInCategory) {
|
|
|
return {
|
|
|
- message: "category-has-products",
|
|
|
+ message: "one-or-more-categories-have-products",
|
|
|
code: 409
|
|
|
};
|
|
|
}
|
|
|
- await Category.findByIdAndDelete(categoryID);
|
|
|
+
|
|
|
+ const result = await Category.deleteMany({
|
|
|
+ _id: {
|
|
|
+ $in: normalizedCategoryIDs
|
|
|
+ },
|
|
|
+ userID: userID
|
|
|
+ });
|
|
|
+
|
|
|
+ if (result.deletedCount === 0) {
|
|
|
+ return {
|
|
|
+ message: "categories-not-found-or-unauthorized",
|
|
|
+ code: 404
|
|
|
+ };
|
|
|
+ }
|
|
|
|
|
|
return {
|
|
|
- message: "category-deleted",
|
|
|
+ message: "categories-deleted",
|
|
|
code: 200
|
|
|
};
|
|
|
} catch (error) {
|
|
|
console.error("DeleteCategory error:", error);
|
|
|
return {
|
|
|
message: "internal-server-error",
|
|
|
- code: 500
|
|
|
+ code: 500
|
|
|
};
|
|
|
}
|
|
|
};
|