All files / payments payments.controller.ts

100% Statements 12/12
100% Branches 0/0
100% Functions 3/3
100% Lines 11/11

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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 783x                   3x                         3x   3x 3x         3x 3x                                                     3x       7x                   3x 6x      
import {
  Body,
  Controller,
  HttpCode,
  HttpStatus,
  Post,
  RawBodyRequest,
  Req,
  UseGuards,
} from '@nestjs/common'
import {
  ApiBadRequestResponse,
  ApiBearerAuth,
  ApiBody,
  ApiCreatedResponse,
  ApiForbiddenResponse,
  ApiInternalServerErrorResponse,
  ApiOperation,
  ApiServiceUnavailableResponse,
  ApiTags,
  ApiUnauthorizedResponse,
} from '@nestjs/swagger'
import { Request } from 'express'
import { JwtGuard } from '../shared/guards/jwt.guard'
import { RequestWithJWTPayload } from '../shared/interfaces/request-with-user.interface'
import { PaymentDTO } from './interfaces/payments'
import { PaymentsService } from './services/payments.service'
 
@ApiTags('payments')
@Controller('payments')
// No Serialization coz we are working with Stripe objects
export class PaymentsController {
  constructor(private paymentService: PaymentsService) {}
 
  @ApiInternalServerErrorResponse({
    description: 'The interaction with Stripe is possibly broken',
  })
  @ApiForbiddenResponse({
    description: 'The change in plan is not allowed',
  })
  @ApiUnauthorizedResponse({
    description: 'Jwt invalid or user does not exist',
  })
  @ApiServiceUnavailableResponse({
    description: ' Payment service is unavailable',
  })
  @ApiBadRequestResponse({
    description: 'Malformed dto passed',
  })
  @ApiOperation({ summary: 'Create a checkout session' })
  @ApiBody({ type: PaymentDTO })
  @UseGuards(JwtGuard)
  @ApiBearerAuth('access_token')
  @Post('checkout')
  @ApiCreatedResponse({
    description:
      'Checkout session created. The return value is the stripe session (Stripe.Response<Stripe.Checkout.Session>)',
    type: Object, // Swagger doesn't work with Stripe objects
  })
  async createCheckoutSession(
    @Body() { plan }: PaymentDTO,
    @Req() { user }: RequestWithJWTPayload,
  ) {
    return await this.paymentService.createCheckoutSession(plan, user.id)
  }
 
  // This is the endpoint for Stripe handled information and receives rawBody data
  @Post('webhook')
  @ApiOperation({
    summary:
      'Endpoint called by stripe backend to communicate transaction outcome',
  })
  @HttpCode(HttpStatus.NO_CONTENT)
  async webhook(@Req() req: RawBodyRequest<Request>) {
    await this.paymentService.handleWebhook(req)
  }
}