Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
✨ Add Stripe invoices endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Oct 31, 2020
1 parent be293ae commit 0dc4b42
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/modules/stripe/stripe-invoices.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Controller, Get, Param, ParseIntPipe, Query } from '@nestjs/common';
import Stripe from 'stripe';
import { CursorPipe } from '../../pipes/cursor.pipe';
import { OptionalIntPipe } from '../../pipes/optional-int.pipe';
import { Scopes } from '../auth/scope.decorator';
import { StripeService } from './stripe.service';

@Controller('groups/:groupId/invoices')
export class StripeBillingController {
constructor(private stripeService: StripeService) {}

@Get()
@Scopes('group-{groupId}:read-invoice')
async getAll(
@Param('groupId', ParseIntPipe) groupId: number,
@Query('take', OptionalIntPipe) take?: number,
@Query('cursor', CursorPipe) cursor?: { id: string },
): Promise<Stripe.Invoice[]> {
return this.stripeService.getInvoices(groupId, { take, cursor });
}

@Get(':id')
@Scopes('group-{groupId}:read-invoice-{id}')
async get(
@Param('groupId', ParseIntPipe) groupId: number,
@Param('id') id: string,
): Promise<Stripe.Invoice> {
return this.stripeService.getInvoice(groupId, id);
}
}
31 changes: 31 additions & 0 deletions src/modules/stripe/stripe.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,37 @@ export class StripeService {
return result;
}

async getInvoices(
groupId: number,
params: {
take?: number;
cursor?: { id: string };
},
): Promise<Stripe.Invoice[]> {
const stripeId = await this.stripeId(groupId);
const result = await this.stripe.invoices.list({
customer: stripeId,
limit: params.take,
starting_after: params.cursor?.id,
});
return this.list<Stripe.Invoice>(result);
}

async getInvoice(
groupId: number,
invoiceId: string,
): Promise<Stripe.Invoice> {
const stripeId = await this.stripeId(groupId);
const result = await this.stripe.invoices.retrieve(invoiceId);
if (result.customer !== stripeId)
throw new NotFoundException('Invoice not found');
return result;
}

private list<T>(result: Stripe.Response<Stripe.ApiList<T>>) {
return result.data;
}

/** Get the Stripe customer ID from a group or throw an error */
private async stripeId(groupId: number): Promise<string> {
const group = await this.prisma.groups.findOne({
Expand Down

0 comments on commit 0dc4b42

Please sign in to comment.