All files / src/routes update.ts

100% Statements 26/26
100% Branches 4/4
100% Functions 2/2
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 303x 3x 3x 3x 3x 3x 3x   3x   3x         5x 5x 4x 4x 3x 2x 1x 1x 1x 1x 1x     3x  
import { BadRequestError, NotFoundError, UnauthorizedError, validateRequest, requireAuth } from '@next-k8s/common'
import express, { Request, Response } from 'express'
import { body } from 'express-validator'
import { isValidObjectId } from 'mongoose'
import Ticket from '../models/ticket'
import TicketUpdatedPublisher from '../events/publishers/updated'
import natsClient from '../nats-client'
 
const router = express.Router()
 
const validateInput = [
  body('title').not().isEmpty().withMessage('Title is required'),
  body('price').isInt({ gt: -1, lt: Number.MAX_SAFE_INTEGER }).withMessage('Price must be an integer of cents or units')
]
 
router.put('/api/tickets/:id', requireAuth, validateInput, validateRequest, async (req: Request, res: Response) => {
  if (!isValidObjectId(req.params.id)) throw new BadRequestError('Invalid Ticket ID')
  const ticket = await Ticket.findById(req.params.id)
  if (!ticket) throw new NotFoundError()
  if (ticket.owner.toHexString() !== req.currentUser!.id) throw new UnauthorizedError()
  if (ticket.orderId) throw new BadRequestError('Ticket is reserved')
  const { title, price } = req.body
  ticket.set({ title, price })
  await ticket.save()
  await new TicketUpdatedPublisher(natsClient.client).publish({ id: ticket.id, version: ticket.version, title: ticket.title, price: ticket.price, owner: ticket.owner })
  res.json(ticket)
})
 
export default router