index.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 categoryCount = await Category.countDocuments({
  15. userID
  16. });
  17. if (categoryCount >= context.categoryLimit) {
  18. return {
  19. message: "category-limit-reached",
  20. code: 403
  21. };
  22. } */
  23. const existing = await Category.findOne({
  24. userID,
  25. index
  26. });
  27. if (existing) {
  28. return {
  29. message: "index-already-in-use",
  30. code: 409
  31. };
  32. }
  33. const newCategory = await Category.create({
  34. userID,
  35. title,
  36. index
  37. });
  38. return {
  39. message: "category-created",
  40. code: 201,
  41. payload: {
  42. category: {
  43. _id: newCategory._id.toString(),
  44. title: newCategory.title,
  45. index: newCategory.index
  46. }
  47. }
  48. };
  49. } catch (error) {
  50. console.error("CreateCategory error:", error);
  51. return {
  52. message: "internal-server-error",
  53. code: 500
  54. };
  55. }
  56. };
  57. export default addCategory;