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

Commit

Permalink
✨ Trigger webhooks on audit log
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Nov 7, 2020
1 parent 74705d6 commit 53ebb4a
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
3 changes: 3 additions & 0 deletions src/interceptors/audit-log.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { STAART_AUDIT_LOG_DATA } from 'src/modules/audit-logs/audit-log.constant
import { UserRequest } from 'src/modules/auth/auth.interface';
import { GeolocationService } from 'src/modules/geolocation/geolocation.service';
import { PrismaService } from 'src/modules/prisma/prisma.service';
import { WebhooksService } from 'src/modules/webhooks/webhooks.service';
import { UAParser } from 'ua-parser-js';

@Injectable()
Expand All @@ -23,6 +24,7 @@ export class AuditLogger implements NestInterceptor {
private readonly reflector: Reflector,
private prisma: PrismaService,
private geolocationService: GeolocationService,
private webhooksService: WebhooksService,
) {}

intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
Expand Down Expand Up @@ -64,6 +66,7 @@ export class AuditLogger implements NestInterceptor {
}`.trim() || undefined,
},
});
this.webhooksService.triggerWebhook(groupId, event);
}
}
})()
Expand Down
57 changes: 52 additions & 5 deletions src/modules/webhooks/webhooks.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
HttpException,
HttpStatus,
Injectable,
Logger,
UnauthorizedException,
} from '@nestjs/common';
import {
Expand All @@ -12,16 +13,18 @@ import {
webhooksWhereInput,
webhooksWhereUniqueInput,
} from '@prisma/client';
import got from 'got';
import PQueue from 'p-queue';
import pRetry from 'p-retry';
import { Expose } from '../prisma/prisma.interface';
import { PrismaService } from '../prisma/prisma.service';
import { StripeService } from '../stripe/stripe.service';

@Injectable()
export class WebhooksService {
constructor(
private prisma: PrismaService,
private stripeService: StripeService,
) {}
private readonly logger = new Logger(WebhooksService.name);
private queue = new PQueue({ concurrency: 1 });

constructor(private prisma: PrismaService) {}

async createWebhook(
groupId: number,
Expand Down Expand Up @@ -116,4 +119,48 @@ export class WebhooksService {
const scopes: Record<string, string> = {};
return scopes;
}

triggerWebhook(groupId: number, event: string) {
this.prisma.webhooks
.findMany({
where: { group: { id: groupId }, isActive: true, event },
})
.then((webhooks) => {
webhooks.forEach((webhook) =>
this.queue
.add(() =>
pRetry(() => this.callWebhook(webhook, event), {
retries: 3,
onFailedAttempt: (error) => {
this.logger.error(
`Triggering webhoook failed, retrying (${error.retriesLeft} attempts left)`,
error.name,
);
if (error.retriesLeft === 0)
this.prisma.webhooks
.update({
where: { id: webhook.id },
data: { isActive: false },
})
.then(() => {})
.catch(() => {});
},
}),
)
.then(() => {})
.catch(() => {}),
);
})
.catch((error) => this.logger.error('Unable to get webhooks', error));
}

private async callWebhook(webhook: webhooks, event: string) {
if (webhook.contentType === 'application/json')
await got(webhook.url, { method: 'POST', json: { event } });
else await got(webhook.url, { method: 'POST', body: event });
await this.prisma.webhooks.update({
where: { id: webhook.id },
data: { lastFiredAt: new Date() },
});
}
}

0 comments on commit 53ebb4a

Please sign in to comment.