index.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import {
  2. Category
  3. } from "../../../models/Category";
  4. import {
  5. AddCategoryInput,
  6. AddCategoryResult
  7. } from "./types";
  8. const addCategory = async (userID: string, input: AddCategoryInput): Promise<AddCategoryResult> => {
  9. try {
  10. const {
  11. title,
  12. index
  13. } = input;
  14. const existing = await Category.findOne({
  15. userID,
  16. index
  17. });
  18. if (existing) {
  19. return {
  20. message: "index-already-in-use",
  21. code: 409
  22. };
  23. }
  24. const newCategory = await Category.create({
  25. userID,
  26. title,
  27. index
  28. });
  29. return {
  30. message: "category-created",
  31. code: 201,
  32. payload: {
  33. category: {
  34. _id: newCategory._id.toString(),
  35. isActive: newCategory.isActive,
  36. title: newCategory.title,
  37. index: newCategory.index
  38. }
  39. }
  40. };
  41. } catch (error) {
  42. console.error("CreateCategory error:", error);
  43. return {
  44. message: "internal-server-error",
  45. code: 500
  46. };
  47. }
  48. };
  49. export default addCategory;