forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathidempotency.interceptor.ts
More file actions
52 lines (45 loc) · 1.8 KB
/
Copy pathidempotency.interceptor.ts
File metadata and controls
52 lines (45 loc) · 1.8 KB
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
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
UnprocessableEntityException,
} from '@nestjs/common';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { IdempotencyService } from './idempotency.service';
@Injectable()
export class IdempotencyInterceptor implements NestInterceptor {
constructor(private readonly idempotencyService: IdempotencyService) { }
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
const request = context.switchToHttp().getRequest();
const response = context.switchToHttp().getResponse<any>();
const idempotencyKey = request.headers['idempotency-key'];
if (!idempotencyKey || typeof idempotencyKey !== 'string') {
return next.handle();
}
const payloadHash = this.idempotencyService.generateHash(request.body);
const existingRecord = await this.idempotencyService.getRecord(idempotencyKey);
if (existingRecord) {
if (existingRecord.requestPayloadHash !== payloadHash) {
throw new UnprocessableEntityException(
'Idempotency key already used with a different payload',
);
}
const body = JSON.parse(existingRecord.responseBody);
response.status(existingRecord.statusCode).set('X-Idempotency-Cache', 'HIT');
return of(body);
}
return next.handle().pipe(
tap(async (data) => {
const statusCode = response.statusCode;
await this.idempotencyService.createRecord(
idempotencyKey,
payloadHash,
data,
statusCode,
);
}),
);
}
}