-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-idempotency.ts
More file actions
156 lines (127 loc) · 4.71 KB
/
Copy pathtest-idempotency.ts
File metadata and controls
156 lines (127 loc) · 4.71 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { generateWebhookSignature } from './src/utils/verifySignature';
import { prisma } from './src/db';
const BASE_URL = 'http://localhost:3000';
interface WebhookPayload {
eventId: string;
type: string;
userId: string;
amount: number;
currency: string;
timestamp: string;
}
interface UserData {
userId: string;
points: number;
}
interface TransactionData {
transactions?: Array<{
transactionId: string;
userId: string;
points: number;
type: string;
timestamp: string;
}>;
}
async function cleanupTestData() {
console.log('Cleaning up test data...');
await prisma.event.deleteMany({
where: {
eventId: {
startsWith: 'test-payment-',
},
},
});
await prisma.transaction.deleteMany({
where: {
eventId: {
startsWith: 'test-payment-',
},
},
});
const testUser = await prisma.user.findUnique({
where: { id: 'user-alice' },
});
if (testUser) {
await prisma.user.update({
where: { id: 'user-alice' },
data: { points: 0 },
});
}
console.log('Cleanup completed.\n');
}
async function sendWebhook(payload: WebhookPayload): Promise<any> {
const payloadString = JSON.stringify(payload);
const signature = generateWebhookSignature(payloadString);
const response = await fetch(`${BASE_URL}/webhooks/payment`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-webhook-signature': signature,
},
body: payloadString,
});
const data = await response.json();
return { status: response.status, data };
}
async function testIdempotency() {
console.log('Testing Webhook Idempotency\n');
console.log('=' .repeat(60));
await cleanupTestData();
const uniqueEventId = `test-payment-${Date.now()}`;
// LEts TEST PAYLOAD
const payload: WebhookPayload = {
eventId: uniqueEventId,
type: 'payment.completed',
userId: 'user-alice',
amount: 10000,
currency: 'USD',
timestamp: new Date().toISOString(),
};
console.log('\nFirst Request - Should create new event and award points');
console.log('Payload:', JSON.stringify(payload, null, 2));
const response1 = await sendWebhook(payload);
console.log('\nResponse 1:');
console.log(` Status: ${response1.status}`);
console.log(` Data:`, JSON.stringify(response1.data, null, 2));
// WAIT A BIT FOR WORKER TO PROCESS
console.log('\nWaiting 2 seconds for worker to process...');
await new Promise(resolve => setTimeout(resolve, 2000));
// SEND SAME WEBHOOK AGAIN
console.log('\nSecond Request - Same eventId (testing idempotency)');
const response2 = await sendWebhook(payload);
console.log('\nResponse 2:');
console.log(` Status: ${response2.status}`);
console.log(` Data:`, JSON.stringify(response2.data, null, 2));
// CHECK USER POINTS
console.log('\nChecking user points...');
const userResponse = await fetch(`${BASE_URL}/users/user-alice`);
const userData = await userResponse.json() as UserData;
console.log(' User Data:', JSON.stringify(userData, null, 2));
// CHECK TRANSACTIONS
console.log('\nChecking transactions...');
const txResponse = await fetch(`${BASE_URL}/transactions?userId=user-alice`);
const txData = await txResponse.json() as TransactionData;
console.log(' Transactions:', JSON.stringify(txData, null, 2));
const txCount = txData.transactions?.length || 0;
console.log('\n' + '='.repeat(60));
console.log('\nIDEMPOTENCY TEST RESULTS:');
console.log(` • First request status: ${response1.status} - ${response1.data.message}`);
console.log(` • Second request status: ${response2.status} - ${response2.data.message}`);
console.log(` • User points: ${userData.points} (should be 100, not 200 for $100 payment)`);
console.log(` • Transaction count: ${txCount} (should be 1, not 2)`);
const firstRequestCreated = response1.status === 202;
const secondRequestRejected = response2.status === 200 && response2.data.message.includes('already received');
const correctPoints = userData.points === 100;
const singleTransaction = txCount === 1;
if (firstRequestCreated && secondRequestRejected && correctPoints && singleTransaction) {
console.log('\nIDEMPOTENCY TEST PASSED! Points awarded only once.');
} else {
console.log('\nIDEMPOTENCY TEST FAILED!');
if (!firstRequestCreated) console.log(' - First request did not create event (expected 202)');
if (!secondRequestRejected) console.log(' - Second request was not rejected as duplicate (expected 200 with "already received")');
if (!correctPoints) console.log(' - Incorrect points awarded');
if (!singleTransaction) console.log(' - Multiple transactions created');
}
await prisma.$disconnect();
}
testIdempotency().catch(console.error);