nodejsdeveloperskh

controller and repository

May 25th, 2021 (edited)
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // controller
  2.  
  3. /**@type {import('express').RequestHandler} */
  4. async function createTicket(req, res, next) {
  5.     const {
  6.         title,
  7.         userId,
  8.         priority,
  9.         departmentId,
  10.         assigneTo,
  11.         description,
  12.     } = req.body;
  13.     const adminId = req.payload.id;
  14.  
  15.     await ticketRepository.insert(
  16.         title,
  17.         userId,
  18.         priority,
  19.         departmentId,
  20.         'admin',
  21.         {
  22.             from: adminId,
  23.             to: assigneTo,
  24.             description,
  25.         },
  26.     );
  27.  
  28.     res.status(200).json({
  29.         successful: true,
  30.         message: 'TICKET_CREATED',
  31.     });
  32. }
  33.  
  34. // repository
  35.  
  36. /**
  37.  *
  38.  * @param {string} title
  39.  * @param {string} userId
  40.  * @param {string} priority
  41.  * @param {string} departmentId
  42.  * @param {'admin'|'contractor'|'lead'} ticketInitializer
  43.  * @param {object} [assignee]
  44.  * @param {object} assignee.from
  45.  * @param {object} assignee.to
  46.  * @param {object} assignee.description
  47.  * @throws {ForeignKeyConstraintsError}
  48.  * @returns {Promise<{ticketId: string}>} created ticket's id
  49.  */
  50. async function insert(
  51.     title,
  52.     userId,
  53.     priority,
  54.     departmentId,
  55.     ticketInitializer,
  56.     assignee = undefined,
  57. ) {
  58.     const {
  59.         ticketDepartment,
  60.     } = await ticketDepartmentRepository.fetchDepartmentById(
  61.         departmentId,
  62.     );
  63.  
  64.     if (!ticketDepartment) {
  65.         throw new ForeignKeyConstraintsError(COLLECTION_NAME, {
  66.             fieldName: 'departmentId',
  67.             fieldValue: departmentId,
  68.         });
  69.     }
  70.     if (!ticketDepartment.members.includes(assignee.to)) {
  71.         throw new MemberNotFound(assignee.to);
  72.     }
  73.  
  74.     const newTicket = await new TicketModel({
  75.         title,
  76.         userId: userId,
  77.         priority,
  78.         departmentId,
  79.         ...(assignee !== undefined
  80.             ? { assigneeHistory: [assignee] }
  81.             : {}),
  82.         ticketInitializer,
  83.     }).save();
  84.  
  85.     return {
  86.         ticketId: newTicket.id,
  87.     };
  88. }
  89.  
  90. // current validator: express-validator
  91. // and other stuff is the same as my project schema
Add Comment
Please, Sign In to add comment