forked from ritik4ever/stellar-goal-vault
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathidempotencyMiddleware.ts
More file actions
66 lines (58 loc) · 1.84 KB
/
Copy pathidempotencyMiddleware.ts
File metadata and controls
66 lines (58 loc) · 1.84 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import type { Request, Response, NextFunction } from 'express';
import {
getIdempotencyCacheEntry,
setIdempotencyCacheEntry,
buildIdempotencyCacheKey,
} from '../services/idempotencyCache';
import type { RequestWithApiKey } from './apiKeyAuth';
interface IdempotencyRequest extends Request {
idempotencyKey?: string;
}
export function idempotencyMiddleware(
req: IdempotencyRequest,
res: Response,
next: NextFunction,
): void {
const idempotencyKey = req.header('Idempotency-Key');
if (!idempotencyKey) {
return next();
}
const apiKey = (req as unknown as RequestWithApiKey).apiKey ?? 'anonymous';
const campaignId = req.params.id as string;
const cacheKey = buildIdempotencyCacheKey(apiKey, campaignId, idempotencyKey);
getIdempotencyCacheEntry(cacheKey).then(
(cached) => {
if (cached) {
res.setHeader('Content-Type', 'application/json');
res.setHeader('X-Idempotency-Cache', 'HIT');
for (const [name, value] of Object.entries(cached.headers)) {
res.setHeader(name, value);
}
res.status(cached.statusCode).send(cached.body);
return;
}
const originalSend = res.send.bind(res);
res.send = function (data: unknown) {
if (res.statusCode >= 200 && res.statusCode < 300) {
const body = typeof data === 'string' ? data : JSON.stringify(data);
const entry = {
statusCode: res.statusCode,
body,
headers: {
'Content-Type': res.getHeader('Content-Type') as string,
},
};
setIdempotencyCacheEntry(cacheKey, entry).catch(() => {
// Silently fail cache writes
});
res.setHeader('X-Idempotency-Cache', 'MISS');
}
return originalSend(data);
};
next();
},
() => {
next();
},
);
}