@nathapp/nestjs-idempotency 4.0.0 → 4.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/interceptor/idempotency.interceptor.js +17 -3
- package/dist/interceptor/idempotency.interceptor.js.map +1 -1
- package/dist/provider/fingerprint.js +15 -6
- package/dist/provider/fingerprint.js.map +1 -1
- package/dist/provider/in-memory-idempotency-store.d.ts +8 -1
- package/dist/provider/in-memory-idempotency-store.js +27 -1
- package/dist/provider/in-memory-idempotency-store.js.map +1 -1
- package/package.json +6 -6
- package/.eslintrc.js +0 -8
- package/.nax/features/nestjs-idempotency/.nax-acceptance.test.ts +0 -766
- package/.nax/features/nestjs-idempotency/.nax-suggested.test.ts +0 -439
- package/.nax/test-debug.ts +0 -22
- package/.turbo/turbo-build.log +0 -4
- package/CHANGELOG.md +0 -42
- package/lib/constant/idempotency.constants.ts +0 -8
- package/lib/constant/index.ts +0 -1
- package/lib/decorator/idempotent.decorator.ts +0 -4
- package/lib/exception/idempotency-exception-code.enum.ts +0 -5
- package/lib/exception/idempotency.exceptions.ts +0 -15
- package/lib/index.ts +0 -13
- package/lib/interceptor/idempotency.interceptor.ts +0 -187
- package/lib/interface/idempotency-module-options.interface.ts +0 -21
- package/lib/interface/idempotency-record.interface.ts +0 -14
- package/lib/interface/idempotency-store.interface.ts +0 -8
- package/lib/module/idempotency.module.ts +0 -61
- package/lib/provider/default-principal-extractor.ts +0 -17
- package/lib/provider/fingerprint.ts +0 -17
- package/lib/provider/in-memory-idempotency-store.ts +0 -53
- package/lib/provider/resolve-idempotency-options.ts +0 -32
- package/test/barrel/index.spec.ts +0 -40
- package/test/constant/idempotency.constants.spec.ts +0 -10
- package/test/decorator/idempotent.decorator.spec.ts +0 -20
- package/test/e2e/express.e2e.spec.ts +0 -219
- package/test/e2e/fastify.e2e.spec.ts +0 -64
- package/test/exception/idempotency.exceptions.spec.ts +0 -24
- package/test/interceptor/idempotency.interceptor.spec.ts +0 -739
- package/test/jest-nax-setup-test.js +0 -21
- package/test/jest-nax-setup.js +0 -92
- package/test/jest-nax.json +0 -30
- package/test/jest-test.json +0 -28
- package/test/module/idempotency.module.spec.ts +0 -87
- package/test/provider/fingerprint.spec.ts +0 -27
- package/test/provider/in-memory-idempotency-store.spec.ts +0 -212
- package/test/provider/resolve-idempotency-options.spec.ts +0 -42
- package/tsconfig.json +0 -9
|
@@ -1,766 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it, beforeAll, afterAll, jest } from '@jest/globals';
|
|
2
|
-
import { lastValueFrom, of, throwError } from 'rxjs';
|
|
3
|
-
import {
|
|
4
|
-
Controller,
|
|
5
|
-
Post,
|
|
6
|
-
Body,
|
|
7
|
-
INestApplication,
|
|
8
|
-
APP_INTERCEPTOR,
|
|
9
|
-
HttpException,
|
|
10
|
-
HttpStatus,
|
|
11
|
-
} from '@nestjs/common';
|
|
12
|
-
import { Test } from '@nestjs/testing';
|
|
13
|
-
import { Reflector, HttpAdapterHost } from '@nestjs/core';
|
|
14
|
-
import { CallHandler, ExecutionContext } from '@nestjs/common';
|
|
15
|
-
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
|
|
16
|
-
import { AppException } from '@nathapp/nestjs-common';
|
|
17
|
-
|
|
18
|
-
import {
|
|
19
|
-
computeFingerprint,
|
|
20
|
-
resolveIdempotencyOptions,
|
|
21
|
-
InMemoryIdempotencyStore,
|
|
22
|
-
Idempotent,
|
|
23
|
-
IDEMPOTENT_METADATA_KEY,
|
|
24
|
-
IdempotencyConflictException,
|
|
25
|
-
IdempotencyKeyReuseException,
|
|
26
|
-
IdempotencyExceptionCode,
|
|
27
|
-
IdempotencyModule,
|
|
28
|
-
IdempotencyInterceptor,
|
|
29
|
-
IDEMPOTENCY_STORE,
|
|
30
|
-
} from '../../../lib';
|
|
31
|
-
import { IDEMPOTENCY_MODULE_OPTIONS } from '../../../lib/constant';
|
|
32
|
-
|
|
33
|
-
// ─── Utilities ───────────────────────────────────────────────────────────────
|
|
34
|
-
|
|
35
|
-
const sha256 = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
|
|
36
|
-
|
|
37
|
-
const makeIdempotentReflector = (hasMetadata: boolean): Reflector =>
|
|
38
|
-
({ get: jest.fn().mockReturnValue(hasMetadata ? true : undefined) }) as unknown as Reflector;
|
|
39
|
-
|
|
40
|
-
const makeNext = (body: unknown, isError = false): CallHandler => ({
|
|
41
|
-
handle: jest.fn().mockReturnValue(isError ? throwError(() => body) : of(body)),
|
|
42
|
-
});
|
|
43
|
-
|
|
44
|
-
const makeContext = (opts: {
|
|
45
|
-
method?: string;
|
|
46
|
-
path?: string;
|
|
47
|
-
headers?: Record<string, string>;
|
|
48
|
-
body?: unknown;
|
|
49
|
-
statusCode?: number;
|
|
50
|
-
responseHeaders?: Record<string, string>;
|
|
51
|
-
handler?: object;
|
|
52
|
-
} = {}): ExecutionContext => {
|
|
53
|
-
const request = {
|
|
54
|
-
method: opts.method ?? 'POST',
|
|
55
|
-
path: opts.path ?? '/users',
|
|
56
|
-
url: opts.path ?? '/users',
|
|
57
|
-
headers: opts.headers ?? { 'idempotency-key': 'test-key-123' },
|
|
58
|
-
body: opts.body ?? { a: 1 },
|
|
59
|
-
};
|
|
60
|
-
const response = {
|
|
61
|
-
statusCode: opts.statusCode ?? 200,
|
|
62
|
-
getHeaders: () => opts.responseHeaders ?? { 'content-type': 'application/json' },
|
|
63
|
-
};
|
|
64
|
-
return {
|
|
65
|
-
getHandler: () => opts.handler ?? {},
|
|
66
|
-
switchToHttp: () => ({ getRequest: () => request, getResponse: () => response }),
|
|
67
|
-
} as unknown as ExecutionContext;
|
|
68
|
-
};
|
|
69
|
-
|
|
70
|
-
const makeStoreMock = (putResult: any = undefined) => ({
|
|
71
|
-
putIfAbsent: jest.fn().mockResolvedValue(putResult),
|
|
72
|
-
complete: jest.fn().mockResolvedValue(undefined),
|
|
73
|
-
remove: jest.fn().mockResolvedValue(undefined),
|
|
74
|
-
get: jest.fn().mockResolvedValue(undefined),
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
const makeHttpAdapterComponents = () => {
|
|
78
|
-
const httpAdapter = { reply: jest.fn(), setHeader: jest.fn() };
|
|
79
|
-
const host = { httpAdapter } as unknown as HttpAdapterHost;
|
|
80
|
-
return { httpAdapter, host };
|
|
81
|
-
};
|
|
82
|
-
|
|
83
|
-
const defaultOptions = {
|
|
84
|
-
headerName: 'Idempotency-Key',
|
|
85
|
-
ttlMs: 86_400_000,
|
|
86
|
-
requireKey: false,
|
|
87
|
-
replayHeaders: ['content-type'],
|
|
88
|
-
};
|
|
89
|
-
|
|
90
|
-
const buildInterceptor = (opts: {
|
|
91
|
-
hasMetadata?: boolean;
|
|
92
|
-
store?: ReturnType<typeof makeStoreMock>;
|
|
93
|
-
requireKey?: boolean;
|
|
94
|
-
httpAdapterHost?: HttpAdapterHost;
|
|
95
|
-
} = {}) => {
|
|
96
|
-
const reflector = makeIdempotentReflector(opts.hasMetadata ?? true);
|
|
97
|
-
const store = opts.store ?? makeStoreMock();
|
|
98
|
-
const { host } = makeHttpAdapterComponents();
|
|
99
|
-
const adapterHost = opts.httpAdapterHost ?? host;
|
|
100
|
-
const options = { ...defaultOptions, requireKey: opts.requireKey ?? false };
|
|
101
|
-
return {
|
|
102
|
-
interceptor: new IdempotencyInterceptor(reflector, store as any, adapterHost, options),
|
|
103
|
-
store,
|
|
104
|
-
};
|
|
105
|
-
};
|
|
106
|
-
|
|
107
|
-
const runIntercept = async (
|
|
108
|
-
interceptor: InstanceType<typeof IdempotencyInterceptor>,
|
|
109
|
-
context: ExecutionContext,
|
|
110
|
-
next: CallHandler,
|
|
111
|
-
): Promise<unknown> => {
|
|
112
|
-
let obs: any;
|
|
113
|
-
try {
|
|
114
|
-
obs = interceptor.intercept(context, next);
|
|
115
|
-
} catch (err) {
|
|
116
|
-
throw err;
|
|
117
|
-
}
|
|
118
|
-
if (obs && typeof obs.subscribe === 'function') {
|
|
119
|
-
return lastValueFrom(obs, { defaultValue: undefined });
|
|
120
|
-
}
|
|
121
|
-
return undefined;
|
|
122
|
-
};
|
|
123
|
-
|
|
124
|
-
const captureInterceptError = async (
|
|
125
|
-
interceptor: InstanceType<typeof IdempotencyInterceptor>,
|
|
126
|
-
context: ExecutionContext,
|
|
127
|
-
next: CallHandler,
|
|
128
|
-
): Promise<any> => {
|
|
129
|
-
try {
|
|
130
|
-
await runIntercept(interceptor, context, next);
|
|
131
|
-
} catch (err) {
|
|
132
|
-
return err;
|
|
133
|
-
}
|
|
134
|
-
throw new Error('Expected interceptor to throw but it did not');
|
|
135
|
-
};
|
|
136
|
-
|
|
137
|
-
// ─── Integration test controllers (module-level to avoid decorator issues) ───
|
|
138
|
-
|
|
139
|
-
let _mainHandlerCount = 0;
|
|
140
|
-
let _mainCounter = 0;
|
|
141
|
-
let _mainBlocked = false;
|
|
142
|
-
let _mainUnblockFn: (() => void) | null = null;
|
|
143
|
-
|
|
144
|
-
@Controller()
|
|
145
|
-
class MainTestController {
|
|
146
|
-
@Post('test')
|
|
147
|
-
@Idempotent()
|
|
148
|
-
async handle(@Body() _body: unknown) {
|
|
149
|
-
_mainHandlerCount++;
|
|
150
|
-
_mainCounter++;
|
|
151
|
-
if (_mainBlocked && _mainUnblockFn === null) {
|
|
152
|
-
await new Promise<void>(r => { _mainUnblockFn = r; });
|
|
153
|
-
}
|
|
154
|
-
return { count: _mainCounter };
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
let _errorHandlerCount = 0;
|
|
159
|
-
|
|
160
|
-
@Controller()
|
|
161
|
-
class ErrorTestController {
|
|
162
|
-
@Post('test')
|
|
163
|
-
@Idempotent()
|
|
164
|
-
handle(@Body() _body: unknown): never {
|
|
165
|
-
_errorHandlerCount++;
|
|
166
|
-
throw new HttpException({ error: 'fail' }, HttpStatus.INTERNAL_SERVER_ERROR);
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
let _fastifyHandlerCount = 0;
|
|
171
|
-
let _fastifyCounter = 0;
|
|
172
|
-
|
|
173
|
-
@Controller()
|
|
174
|
-
class FastifyTestController {
|
|
175
|
-
@Post('test')
|
|
176
|
-
@Idempotent()
|
|
177
|
-
handle(@Body() _body: unknown) {
|
|
178
|
-
_fastifyHandlerCount++;
|
|
179
|
-
_fastifyCounter++;
|
|
180
|
-
return { count: _fastifyCounter };
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
185
|
-
// US-001: Primitives
|
|
186
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
187
|
-
|
|
188
|
-
describe('US-001: Idempotency primitives', () => {
|
|
189
|
-
it('AC-1: computeFingerprint produces equal 64-char hex strings for objects with same fields in different key order', () => {
|
|
190
|
-
const a = computeFingerprint({ a: 1, b: 2 });
|
|
191
|
-
const b = computeFingerprint({ b: 2, a: 1 });
|
|
192
|
-
expect(a).toStrictEqual(b);
|
|
193
|
-
expect(a).toMatch(/^[a-f0-9]{64}$/);
|
|
194
|
-
expect(b).toMatch(/^[a-f0-9]{64}$/);
|
|
195
|
-
});
|
|
196
|
-
|
|
197
|
-
it('AC-2: computeFingerprint returns different values for arrays with different element order', () => {
|
|
198
|
-
const a = computeFingerprint({ list: [1, 2] });
|
|
199
|
-
const b = computeFingerprint({ list: [2, 1] });
|
|
200
|
-
expect(a).not.toStrictEqual(b);
|
|
201
|
-
});
|
|
202
|
-
|
|
203
|
-
it('AC-3: computeFingerprint(undefined) does not throw and returns a stable non-empty hex string', () => {
|
|
204
|
-
let first!: string;
|
|
205
|
-
expect(() => { first = computeFingerprint(undefined); }).not.toThrow();
|
|
206
|
-
expect(first).toMatch(/^[a-f0-9]+$/);
|
|
207
|
-
expect(first.length).toBeGreaterThan(0);
|
|
208
|
-
const second = computeFingerprint(undefined);
|
|
209
|
-
expect(second).toStrictEqual(first);
|
|
210
|
-
});
|
|
211
|
-
|
|
212
|
-
it('AC-4: resolveIdempotencyOptions(undefined) returns correct defaults', () => {
|
|
213
|
-
const opts = resolveIdempotencyOptions(undefined);
|
|
214
|
-
expect(opts.headerName).toBe('Idempotency-Key');
|
|
215
|
-
expect(opts.ttlMs).toBe(86_400_000);
|
|
216
|
-
expect(opts.requireKey).toBe(false);
|
|
217
|
-
expect(JSON.stringify(opts.replayHeaders)).toBe(JSON.stringify(['content-type']));
|
|
218
|
-
});
|
|
219
|
-
|
|
220
|
-
it('AC-5: resolveIdempotencyOptions({}) returns a store that is instanceof InMemoryIdempotencyStore', () => {
|
|
221
|
-
const opts = resolveIdempotencyOptions({});
|
|
222
|
-
expect(opts.store).toBeInstanceOf(InMemoryIdempotencyStore);
|
|
223
|
-
});
|
|
224
|
-
|
|
225
|
-
it('AC-6: resolveIdempotencyOptions with explicit values returns those values unchanged', () => {
|
|
226
|
-
const opts = resolveIdempotencyOptions({
|
|
227
|
-
headerName: 'X-Key',
|
|
228
|
-
ttlMs: 1000,
|
|
229
|
-
requireKey: true,
|
|
230
|
-
replayHeaders: ['content-type', 'location'],
|
|
231
|
-
});
|
|
232
|
-
expect(opts.headerName).toBe('X-Key');
|
|
233
|
-
expect(opts.ttlMs).toBe(1000);
|
|
234
|
-
expect(opts.requireKey).toBe(true);
|
|
235
|
-
expect(JSON.stringify(opts.replayHeaders)).toBe(JSON.stringify(['content-type', 'location']));
|
|
236
|
-
});
|
|
237
|
-
|
|
238
|
-
it('AC-7: resolveIdempotencyOptions({ store: customStore }) returns the exact same store instance', () => {
|
|
239
|
-
const customStore = {
|
|
240
|
-
putIfAbsent: jest.fn(),
|
|
241
|
-
complete: jest.fn(),
|
|
242
|
-
remove: jest.fn(),
|
|
243
|
-
get: jest.fn(),
|
|
244
|
-
};
|
|
245
|
-
const opts = resolveIdempotencyOptions({ store: customStore as any });
|
|
246
|
-
expect(opts.store).toBe(customStore);
|
|
247
|
-
});
|
|
248
|
-
|
|
249
|
-
it('AC-8: @Idempotent() sets reflected metadata true on the decorated method; undecorated returns undefined', () => {
|
|
250
|
-
class TestClass {
|
|
251
|
-
@Idempotent()
|
|
252
|
-
decorated() { return; }
|
|
253
|
-
|
|
254
|
-
undecorated() { return; }
|
|
255
|
-
}
|
|
256
|
-
const reflector = new Reflector();
|
|
257
|
-
expect(reflector.get(IDEMPOTENT_METADATA_KEY, TestClass.prototype.decorated)).toBe(true);
|
|
258
|
-
expect(reflector.get(IDEMPOTENT_METADATA_KEY, TestClass.prototype.undecorated)).toBeUndefined();
|
|
259
|
-
});
|
|
260
|
-
|
|
261
|
-
it('AC-9: IdempotencyConflictException is AppException with httpStatus 409 and CONFLICT_IN_FLIGHT === 40900', () => {
|
|
262
|
-
const ex = new IdempotencyConflictException();
|
|
263
|
-
expect(ex).toBeInstanceOf(AppException);
|
|
264
|
-
expect(ex.httpStatus).toBe(409);
|
|
265
|
-
expect(ex.code).toBe(IdempotencyExceptionCode.CONFLICT_IN_FLIGHT);
|
|
266
|
-
expect(IdempotencyExceptionCode.CONFLICT_IN_FLIGHT).toBe(40900);
|
|
267
|
-
});
|
|
268
|
-
|
|
269
|
-
it('AC-10: IdempotencyKeyReuseException is AppException with httpStatus 422 and KEY_REUSE_MISMATCH === 40901', () => {
|
|
270
|
-
const ex = new IdempotencyKeyReuseException();
|
|
271
|
-
expect(ex).toBeInstanceOf(AppException);
|
|
272
|
-
expect(ex.httpStatus).toBe(422);
|
|
273
|
-
expect(ex.code).toBe(IdempotencyExceptionCode.KEY_REUSE_MISMATCH);
|
|
274
|
-
expect(IdempotencyExceptionCode.KEY_REUSE_MISMATCH).toBe(40901);
|
|
275
|
-
});
|
|
276
|
-
|
|
277
|
-
it('AC-11: IDEMPOTENCY_STORE and IDEMPOTENCY_MODULE_OPTIONS are defined; IDEMPOTENCY_STORE === Symbol.for("IDEMPOTENCY_STORE")', () => {
|
|
278
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
279
|
-
const { IDEMPOTENCY_STORE: S, IDEMPOTENCY_MODULE_OPTIONS: O } = require('../../../lib/constant');
|
|
280
|
-
expect(S).toBeDefined();
|
|
281
|
-
expect(O).toBeDefined();
|
|
282
|
-
expect(S).toBe(Symbol.for('IDEMPOTENCY_STORE'));
|
|
283
|
-
});
|
|
284
|
-
});
|
|
285
|
-
|
|
286
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
287
|
-
// US-002: InMemoryIdempotencyStore
|
|
288
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
289
|
-
|
|
290
|
-
describe('US-002: InMemoryIdempotencyStore', () => {
|
|
291
|
-
const makeRecord = (fingerprint = 'fp1', state: 'pending' | 'completed' = 'pending') => ({
|
|
292
|
-
state,
|
|
293
|
-
fingerprint,
|
|
294
|
-
createdAt: Date.now(),
|
|
295
|
-
});
|
|
296
|
-
|
|
297
|
-
it('AC-12: putIfAbsent on a fresh store returns undefined (slot acquired)', async () => {
|
|
298
|
-
const store = new InMemoryIdempotencyStore({ ttlMs: 86_400_000 });
|
|
299
|
-
const result = await store.putIfAbsent('k', makeRecord());
|
|
300
|
-
expect(result).toBeUndefined();
|
|
301
|
-
});
|
|
302
|
-
|
|
303
|
-
it('AC-13: second putIfAbsent with same key returns a record matching the first (not the second)', async () => {
|
|
304
|
-
const store = new InMemoryIdempotencyStore({ ttlMs: 86_400_000 });
|
|
305
|
-
const recordA = makeRecord('fp-a');
|
|
306
|
-
recordA.createdAt = Date.now(); // fixed for comparison
|
|
307
|
-
const recordB = makeRecord('fp-b');
|
|
308
|
-
await store.putIfAbsent('k', recordA);
|
|
309
|
-
const result = await store.putIfAbsent('k', recordB);
|
|
310
|
-
expect(result).toBeDefined();
|
|
311
|
-
expect(result!.state).toBe(recordA.state);
|
|
312
|
-
expect(result!.fingerprint).toBe(recordA.fingerprint);
|
|
313
|
-
expect(result!.createdAt).toBe(recordA.createdAt);
|
|
314
|
-
});
|
|
315
|
-
|
|
316
|
-
it('AC-14: get("k") after putIfAbsent returns state pending and the stored fingerprint', async () => {
|
|
317
|
-
const store = new InMemoryIdempotencyStore({ ttlMs: 86_400_000 });
|
|
318
|
-
const record = makeRecord('fp-test');
|
|
319
|
-
await store.putIfAbsent('k', record);
|
|
320
|
-
const result = await store.get('k');
|
|
321
|
-
expect(result).toBeDefined();
|
|
322
|
-
expect(result!.state).toBe('pending');
|
|
323
|
-
expect(result!.fingerprint).toBe('fp-test');
|
|
324
|
-
});
|
|
325
|
-
|
|
326
|
-
it('AC-15: get("missing") on a fresh store returns undefined', async () => {
|
|
327
|
-
const store = new InMemoryIdempotencyStore({ ttlMs: 86_400_000 });
|
|
328
|
-
expect(await store.get('missing')).toBeUndefined();
|
|
329
|
-
});
|
|
330
|
-
|
|
331
|
-
it('AC-16: after putIfAbsent then complete, get returns completed record with stored response fields', async () => {
|
|
332
|
-
const store = new InMemoryIdempotencyStore({ ttlMs: 86_400_000 });
|
|
333
|
-
await store.putIfAbsent('k', makeRecord());
|
|
334
|
-
const response = { status: 200, body: { id: 1 }, headers: { 'content-type': 'application/json' } };
|
|
335
|
-
await store.complete('k', response);
|
|
336
|
-
const result = await store.get('k');
|
|
337
|
-
expect(result).toBeDefined();
|
|
338
|
-
expect(result!.state).toBe('completed');
|
|
339
|
-
expect(result!.response!.status).toBe(response.status);
|
|
340
|
-
expect(result!.response!.body).toEqual(response.body);
|
|
341
|
-
expect(result!.response!.headers).toEqual(response.headers);
|
|
342
|
-
});
|
|
343
|
-
|
|
344
|
-
it('AC-17: after putIfAbsent then remove, get returns undefined and a new putIfAbsent returns undefined', async () => {
|
|
345
|
-
const store = new InMemoryIdempotencyStore({ ttlMs: 86_400_000 });
|
|
346
|
-
await store.putIfAbsent('k', makeRecord());
|
|
347
|
-
await store.remove('k');
|
|
348
|
-
expect(await store.get('k')).toBeUndefined();
|
|
349
|
-
const reacquired = await store.putIfAbsent('k', makeRecord('fp2'));
|
|
350
|
-
expect(reacquired).toBeUndefined();
|
|
351
|
-
});
|
|
352
|
-
|
|
353
|
-
it('AC-18: store with ttlMs 0 treats entries as immediately expired (get and putIfAbsent behave as absent)', async () => {
|
|
354
|
-
const store = new InMemoryIdempotencyStore({ ttlMs: 0 });
|
|
355
|
-
await store.putIfAbsent('k', makeRecord());
|
|
356
|
-
expect(await store.get('k')).toBeUndefined();
|
|
357
|
-
const fresh = await store.putIfAbsent('k', makeRecord('fp-fresh'));
|
|
358
|
-
expect(fresh).toBeUndefined();
|
|
359
|
-
});
|
|
360
|
-
});
|
|
361
|
-
|
|
362
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
363
|
-
// US-003: IdempotencyInterceptor
|
|
364
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
365
|
-
|
|
366
|
-
describe('US-003: IdempotencyInterceptor', () => {
|
|
367
|
-
it('AC-19: handler without @Idempotent() — next.handle() called once, putIfAbsent never called', async () => {
|
|
368
|
-
const store = makeStoreMock();
|
|
369
|
-
const { interceptor } = buildInterceptor({ hasMetadata: false, store });
|
|
370
|
-
const next = makeNext('response');
|
|
371
|
-
await runIntercept(interceptor, makeContext(), next);
|
|
372
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(1);
|
|
373
|
-
expect(store.putIfAbsent).not.toHaveBeenCalled();
|
|
374
|
-
});
|
|
375
|
-
|
|
376
|
-
it('AC-20: @Idempotent() + requireKey false + no header — next.handle() called once, putIfAbsent never called', async () => {
|
|
377
|
-
const store = makeStoreMock();
|
|
378
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store, requireKey: false });
|
|
379
|
-
const next = makeNext('response');
|
|
380
|
-
await runIntercept(interceptor, makeContext({ headers: {} }), next);
|
|
381
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(1);
|
|
382
|
-
expect(store.putIfAbsent).not.toHaveBeenCalled();
|
|
383
|
-
});
|
|
384
|
-
|
|
385
|
-
it('AC-21: @Idempotent() + requireKey true + no header — throws AppException 400, next never called, putIfAbsent never called', async () => {
|
|
386
|
-
const store = makeStoreMock();
|
|
387
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store, requireKey: true });
|
|
388
|
-
const next = makeNext('response');
|
|
389
|
-
const err = await captureInterceptError(interceptor, makeContext({ headers: {} }), next);
|
|
390
|
-
expect(err).toBeInstanceOf(AppException);
|
|
391
|
-
expect(err.httpStatus).toBe(400);
|
|
392
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(0);
|
|
393
|
-
expect(store.putIfAbsent).not.toHaveBeenCalled();
|
|
394
|
-
});
|
|
395
|
-
|
|
396
|
-
it('AC-22: header present + putIfAbsent → undefined: next.handle() called, storageKey is deterministic hash of method+path+key', async () => {
|
|
397
|
-
const store = makeStoreMock(undefined);
|
|
398
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
399
|
-
const body = { a: 1 };
|
|
400
|
-
const next = makeNext(body);
|
|
401
|
-
const context = makeContext({
|
|
402
|
-
method: 'POST',
|
|
403
|
-
path: '/users',
|
|
404
|
-
headers: { 'idempotency-key': 'test-key-123' },
|
|
405
|
-
body,
|
|
406
|
-
statusCode: 200,
|
|
407
|
-
});
|
|
408
|
-
await runIntercept(interceptor, context, next);
|
|
409
|
-
|
|
410
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(1);
|
|
411
|
-
expect(store.putIfAbsent).toHaveBeenCalledTimes(1);
|
|
412
|
-
|
|
413
|
-
const storageKey = (store.putIfAbsent as jest.Mock).mock.calls[0][0] as string;
|
|
414
|
-
const expectedKey = sha256('POST\n/users\ntest-key-123');
|
|
415
|
-
expect(storageKey).toBe(expectedKey);
|
|
416
|
-
// Different method yields different key
|
|
417
|
-
expect(sha256('GET\n/users\ntest-key-123')).not.toBe(expectedKey);
|
|
418
|
-
|
|
419
|
-
const record = (store.putIfAbsent as jest.Mock).mock.calls[0][1] as any;
|
|
420
|
-
expect(record.state).toBe('pending');
|
|
421
|
-
expect(record.fingerprint).toBe(computeFingerprint(body));
|
|
422
|
-
});
|
|
423
|
-
|
|
424
|
-
it('AC-23: 2xx handler completion — store.complete called once with 2xx status and body, store.remove never called', async () => {
|
|
425
|
-
const store = makeStoreMock(undefined);
|
|
426
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
427
|
-
const responseBody = { id: 42 };
|
|
428
|
-
const next = makeNext(responseBody);
|
|
429
|
-
await runIntercept(
|
|
430
|
-
interceptor,
|
|
431
|
-
makeContext({ statusCode: 200, body: { a: 1 }, responseHeaders: { 'content-type': 'application/json' } }),
|
|
432
|
-
next,
|
|
433
|
-
);
|
|
434
|
-
expect(store.complete).toHaveBeenCalledTimes(1);
|
|
435
|
-
const [, completedResponse] = (store.complete as jest.Mock).mock.calls[0] as [string, any];
|
|
436
|
-
expect(completedResponse.status).toBeGreaterThanOrEqual(200);
|
|
437
|
-
expect(completedResponse.status).toBeLessThan(300);
|
|
438
|
-
expect(store.remove).not.toHaveBeenCalled();
|
|
439
|
-
});
|
|
440
|
-
|
|
441
|
-
it('AC-24: handler throws — store.remove called once, store.complete never called, original error propagates unchanged', async () => {
|
|
442
|
-
const store = makeStoreMock(undefined);
|
|
443
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
444
|
-
const handlerError = new Error('handler failure');
|
|
445
|
-
const next = makeNext(handlerError, true);
|
|
446
|
-
let caughtError: unknown;
|
|
447
|
-
try {
|
|
448
|
-
await runIntercept(interceptor, makeContext(), next);
|
|
449
|
-
} catch (err) {
|
|
450
|
-
caughtError = err;
|
|
451
|
-
}
|
|
452
|
-
expect(store.remove).toHaveBeenCalledTimes(1);
|
|
453
|
-
expect(store.complete).not.toHaveBeenCalled();
|
|
454
|
-
expect(caughtError).toBe(handlerError);
|
|
455
|
-
});
|
|
456
|
-
|
|
457
|
-
it('AC-25: putIfAbsent returns pending record with matching fingerprint — throws IdempotencyConflictException 409, next never called', async () => {
|
|
458
|
-
const body = { a: 1 };
|
|
459
|
-
const matchingFingerprint = computeFingerprint(body);
|
|
460
|
-
const existingRecord = { state: 'pending' as const, fingerprint: matchingFingerprint, createdAt: Date.now() };
|
|
461
|
-
const store = makeStoreMock(existingRecord);
|
|
462
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
463
|
-
const next = makeNext('response');
|
|
464
|
-
const err = await captureInterceptError(interceptor, makeContext({ body }), next);
|
|
465
|
-
expect(err).toBeInstanceOf(IdempotencyConflictException);
|
|
466
|
-
expect(err.httpStatus).toBe(409);
|
|
467
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(0);
|
|
468
|
-
expect(store.complete).not.toHaveBeenCalled();
|
|
469
|
-
expect(store.remove).not.toHaveBeenCalled();
|
|
470
|
-
});
|
|
471
|
-
|
|
472
|
-
it('AC-26: putIfAbsent returns record with different fingerprint — throws IdempotencyKeyReuseException 422, next never called', async () => {
|
|
473
|
-
const bodyA = { a: 1 };
|
|
474
|
-
const bodyB = { a: 2 };
|
|
475
|
-
const existingRecord = {
|
|
476
|
-
state: 'pending' as const,
|
|
477
|
-
fingerprint: computeFingerprint(bodyB),
|
|
478
|
-
createdAt: Date.now(),
|
|
479
|
-
};
|
|
480
|
-
const store = makeStoreMock(existingRecord);
|
|
481
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
482
|
-
const next = makeNext('response');
|
|
483
|
-
const err = await captureInterceptError(interceptor, makeContext({ body: bodyA }), next);
|
|
484
|
-
expect(err).toBeInstanceOf(IdempotencyKeyReuseException);
|
|
485
|
-
expect(err.httpStatus).toBe(422);
|
|
486
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(0);
|
|
487
|
-
expect(store.complete).not.toHaveBeenCalled();
|
|
488
|
-
expect(store.remove).not.toHaveBeenCalled();
|
|
489
|
-
});
|
|
490
|
-
|
|
491
|
-
it('AC-27: putIfAbsent returns completed record — httpAdapter.reply + setHeader called, next never called, store methods not called', async () => {
|
|
492
|
-
const storedResponse = {
|
|
493
|
-
status: 200,
|
|
494
|
-
body: { id: 1 },
|
|
495
|
-
headers: { 'content-type': 'application/json' },
|
|
496
|
-
};
|
|
497
|
-
const completedRecord = {
|
|
498
|
-
state: 'completed' as const,
|
|
499
|
-
fingerprint: computeFingerprint({ a: 1 }),
|
|
500
|
-
createdAt: Date.now(),
|
|
501
|
-
response: storedResponse,
|
|
502
|
-
};
|
|
503
|
-
const store = makeStoreMock(completedRecord);
|
|
504
|
-
const { httpAdapter, host } = makeHttpAdapterComponents();
|
|
505
|
-
const reflector = makeIdempotentReflector(true);
|
|
506
|
-
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, defaultOptions);
|
|
507
|
-
const next = makeNext('ignored');
|
|
508
|
-
|
|
509
|
-
await runIntercept(interceptor, makeContext(), next);
|
|
510
|
-
|
|
511
|
-
expect(httpAdapter.reply).toHaveBeenCalledTimes(1);
|
|
512
|
-
const replyArgs = (httpAdapter.reply as jest.Mock).mock.calls[0] as [any, any, any];
|
|
513
|
-
expect(replyArgs[1]).toEqual(storedResponse.body);
|
|
514
|
-
expect(replyArgs[2]).toBe(storedResponse.status);
|
|
515
|
-
expect(httpAdapter.setHeader).toHaveBeenCalledWith(
|
|
516
|
-
expect.anything(),
|
|
517
|
-
'content-type',
|
|
518
|
-
'application/json',
|
|
519
|
-
);
|
|
520
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(0);
|
|
521
|
-
expect(store.complete).not.toHaveBeenCalled();
|
|
522
|
-
expect(store.remove).not.toHaveBeenCalled();
|
|
523
|
-
});
|
|
524
|
-
});
|
|
525
|
-
|
|
526
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
527
|
-
// US-004: Module assembly and barrel exports
|
|
528
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
529
|
-
|
|
530
|
-
describe('US-004: Module assembly and barrel exports', () => {
|
|
531
|
-
it('AC-28: IdempotencyModule.register() returns DynamicModule with global true and module === IdempotencyModule', () => {
|
|
532
|
-
const mod = IdempotencyModule.register() as any;
|
|
533
|
-
expect(mod.global).toBe(true);
|
|
534
|
-
expect(mod.module).toBe(IdempotencyModule);
|
|
535
|
-
});
|
|
536
|
-
|
|
537
|
-
it('AC-29: testing module with register() resolves IDEMPOTENCY_STORE to InMemoryIdempotencyStore', async () => {
|
|
538
|
-
const moduleRef = await Test.createTestingModule({
|
|
539
|
-
imports: [IdempotencyModule.register()],
|
|
540
|
-
}).compile();
|
|
541
|
-
expect(moduleRef.get(IDEMPOTENCY_STORE)).toBeInstanceOf(InMemoryIdempotencyStore);
|
|
542
|
-
});
|
|
543
|
-
|
|
544
|
-
it('AC-30: register({ store: customStore }) resolves IDEMPOTENCY_STORE to the exact customStore instance', async () => {
|
|
545
|
-
const customStore = { putIfAbsent: jest.fn(), complete: jest.fn(), remove: jest.fn(), get: jest.fn() };
|
|
546
|
-
const moduleRef = await Test.createTestingModule({
|
|
547
|
-
imports: [IdempotencyModule.register({ store: customStore as any })],
|
|
548
|
-
}).compile();
|
|
549
|
-
expect(moduleRef.get(IDEMPOTENCY_STORE)).toBe(customStore);
|
|
550
|
-
});
|
|
551
|
-
|
|
552
|
-
it('AC-31: registerAsync with useFactory resolves options with headerName "X-Key"', async () => {
|
|
553
|
-
const moduleRef = await Test.createTestingModule({
|
|
554
|
-
imports: [
|
|
555
|
-
IdempotencyModule.registerAsync({
|
|
556
|
-
inject: [],
|
|
557
|
-
useFactory: () => Promise.resolve({ headerName: 'X-Key' }),
|
|
558
|
-
}),
|
|
559
|
-
],
|
|
560
|
-
}).compile();
|
|
561
|
-
const options = moduleRef.get(IDEMPOTENCY_MODULE_OPTIONS) as any;
|
|
562
|
-
expect(options.headerName).toBe('X-Key');
|
|
563
|
-
});
|
|
564
|
-
|
|
565
|
-
it('AC-32: all six barrel exports are importable and of the correct kind', () => {
|
|
566
|
-
expect(IdempotencyModule).toBeInstanceOf(Function);
|
|
567
|
-
expect(IdempotencyInterceptor).toBeInstanceOf(Function);
|
|
568
|
-
expect(typeof Idempotent).toBe('function');
|
|
569
|
-
expect(new InMemoryIdempotencyStore()).toBeInstanceOf(InMemoryIdempotencyStore);
|
|
570
|
-
expect(new IdempotencyConflictException()).toBeInstanceOf(IdempotencyConflictException);
|
|
571
|
-
expect(new IdempotencyKeyReuseException()).toBeInstanceOf(IdempotencyKeyReuseException);
|
|
572
|
-
});
|
|
573
|
-
});
|
|
574
|
-
|
|
575
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
576
|
-
// US-004: Express integration
|
|
577
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
578
|
-
|
|
579
|
-
describe('US-004: Express integration — replay and pass-through', () => {
|
|
580
|
-
let app: INestApplication;
|
|
581
|
-
|
|
582
|
-
beforeAll(async () => {
|
|
583
|
-
_mainHandlerCount = 0;
|
|
584
|
-
_mainCounter = 0;
|
|
585
|
-
_mainBlocked = false;
|
|
586
|
-
_mainUnblockFn = null;
|
|
587
|
-
const moduleRef = await Test.createTestingModule({
|
|
588
|
-
imports: [IdempotencyModule.register()],
|
|
589
|
-
controllers: [MainTestController],
|
|
590
|
-
providers: [{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor }],
|
|
591
|
-
}).compile();
|
|
592
|
-
app = moduleRef.createNestApplication();
|
|
593
|
-
await app.init();
|
|
594
|
-
});
|
|
595
|
-
|
|
596
|
-
afterAll(async () => { await app?.close(); });
|
|
597
|
-
|
|
598
|
-
it('AC-33: two sequential requests with same Idempotency-Key and body — handler called once, both responses identical 200', async () => {
|
|
599
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
600
|
-
const supertest = require('supertest');
|
|
601
|
-
const countBefore = _mainHandlerCount;
|
|
602
|
-
const first = await supertest(app.getHttpServer())
|
|
603
|
-
.post('/test')
|
|
604
|
-
.set('Idempotency-Key', 'K1')
|
|
605
|
-
.send({ a: 1 });
|
|
606
|
-
const second = await supertest(app.getHttpServer())
|
|
607
|
-
.post('/test')
|
|
608
|
-
.set('Idempotency-Key', 'K1')
|
|
609
|
-
.send({ a: 1 });
|
|
610
|
-
expect(first.statusCode).toBe(200);
|
|
611
|
-
expect(second.statusCode).toBe(200);
|
|
612
|
-
expect(second.body).toEqual(first.body);
|
|
613
|
-
expect(_mainHandlerCount).toBe(countBefore + 1);
|
|
614
|
-
});
|
|
615
|
-
|
|
616
|
-
it('AC-37: request without Idempotency-Key header executes normally and returns handler output', async () => {
|
|
617
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
618
|
-
const supertest = require('supertest');
|
|
619
|
-
const countBefore = _mainHandlerCount;
|
|
620
|
-
const res = await supertest(app.getHttpServer()).post('/test').send({ a: 99 });
|
|
621
|
-
expect(res.statusCode).toBe(200);
|
|
622
|
-
expect(res.body).toBeDefined();
|
|
623
|
-
expect(res.body.count).toBeDefined();
|
|
624
|
-
expect(_mainHandlerCount).toBe(countBefore + 1);
|
|
625
|
-
});
|
|
626
|
-
});
|
|
627
|
-
|
|
628
|
-
describe('US-004: Express integration — concurrent 409 and body-mismatch 422', () => {
|
|
629
|
-
let app: INestApplication;
|
|
630
|
-
|
|
631
|
-
beforeAll(async () => {
|
|
632
|
-
_mainHandlerCount = 0;
|
|
633
|
-
_mainCounter = 0;
|
|
634
|
-
_mainBlocked = false;
|
|
635
|
-
_mainUnblockFn = null;
|
|
636
|
-
const moduleRef = await Test.createTestingModule({
|
|
637
|
-
imports: [IdempotencyModule.register()],
|
|
638
|
-
controllers: [MainTestController],
|
|
639
|
-
providers: [{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor }],
|
|
640
|
-
}).compile();
|
|
641
|
-
app = moduleRef.createNestApplication();
|
|
642
|
-
await app.init();
|
|
643
|
-
});
|
|
644
|
-
|
|
645
|
-
afterAll(async () => { await app?.close(); });
|
|
646
|
-
|
|
647
|
-
it('AC-34: concurrent requests with same key while first is in-flight — second gets 409', async () => {
|
|
648
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
649
|
-
const supertest = require('supertest');
|
|
650
|
-
_mainBlocked = true;
|
|
651
|
-
_mainUnblockFn = null;
|
|
652
|
-
|
|
653
|
-
const firstPromise = supertest(app.getHttpServer())
|
|
654
|
-
.post('/test')
|
|
655
|
-
.set('Idempotency-Key', 'K2')
|
|
656
|
-
.send({ a: 1 });
|
|
657
|
-
|
|
658
|
-
// Wait for the first request to be registered as pending in the store
|
|
659
|
-
await new Promise(r => setTimeout(r, 80));
|
|
660
|
-
|
|
661
|
-
const second = await supertest(app.getHttpServer())
|
|
662
|
-
.post('/test')
|
|
663
|
-
.set('Idempotency-Key', 'K2')
|
|
664
|
-
.send({ a: 1 });
|
|
665
|
-
expect(second.statusCode).toBe(409);
|
|
666
|
-
|
|
667
|
-
// Release the first request
|
|
668
|
-
_mainUnblockFn?.();
|
|
669
|
-
_mainBlocked = false;
|
|
670
|
-
const first = await firstPromise;
|
|
671
|
-
expect(first.statusCode).toBe(200);
|
|
672
|
-
});
|
|
673
|
-
|
|
674
|
-
it('AC-35: same key but different body — second request gets 422', async () => {
|
|
675
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
676
|
-
const supertest = require('supertest');
|
|
677
|
-
_mainBlocked = false;
|
|
678
|
-
const first = await supertest(app.getHttpServer())
|
|
679
|
-
.post('/test')
|
|
680
|
-
.set('Idempotency-Key', 'K3')
|
|
681
|
-
.send({ a: 1 });
|
|
682
|
-
expect(first.statusCode).toBe(200);
|
|
683
|
-
|
|
684
|
-
const second = await supertest(app.getHttpServer())
|
|
685
|
-
.post('/test')
|
|
686
|
-
.set('Idempotency-Key', 'K3')
|
|
687
|
-
.send({ a: 2 });
|
|
688
|
-
expect(second.statusCode).toBe(422);
|
|
689
|
-
});
|
|
690
|
-
});
|
|
691
|
-
|
|
692
|
-
describe('US-004: Express integration — non-2xx response not cached', () => {
|
|
693
|
-
let app: INestApplication;
|
|
694
|
-
|
|
695
|
-
beforeAll(async () => {
|
|
696
|
-
_errorHandlerCount = 0;
|
|
697
|
-
const moduleRef = await Test.createTestingModule({
|
|
698
|
-
imports: [IdempotencyModule.register()],
|
|
699
|
-
controllers: [ErrorTestController],
|
|
700
|
-
providers: [{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor }],
|
|
701
|
-
}).compile();
|
|
702
|
-
app = moduleRef.createNestApplication();
|
|
703
|
-
await app.init();
|
|
704
|
-
});
|
|
705
|
-
|
|
706
|
-
afterAll(async () => { await app?.close(); });
|
|
707
|
-
|
|
708
|
-
it('AC-36: handler returning 500 — second request with same key also invokes handler (failed attempt not cached)', async () => {
|
|
709
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
710
|
-
const supertest = require('supertest');
|
|
711
|
-
const first = await supertest(app.getHttpServer())
|
|
712
|
-
.post('/test')
|
|
713
|
-
.set('Idempotency-Key', 'K4')
|
|
714
|
-
.send({});
|
|
715
|
-
expect(first.statusCode).toBe(500);
|
|
716
|
-
|
|
717
|
-
const second = await supertest(app.getHttpServer())
|
|
718
|
-
.post('/test')
|
|
719
|
-
.set('Idempotency-Key', 'K4')
|
|
720
|
-
.send({});
|
|
721
|
-
expect(second.statusCode).toBe(500);
|
|
722
|
-
expect(_errorHandlerCount).toBe(2);
|
|
723
|
-
});
|
|
724
|
-
});
|
|
725
|
-
|
|
726
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
727
|
-
// US-004: Fastify integration
|
|
728
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
729
|
-
|
|
730
|
-
describe('US-004: Fastify integration — replay via HttpAdapterHost', () => {
|
|
731
|
-
let app: NestFastifyApplication;
|
|
732
|
-
|
|
733
|
-
beforeAll(async () => {
|
|
734
|
-
_fastifyHandlerCount = 0;
|
|
735
|
-
_fastifyCounter = 0;
|
|
736
|
-
const moduleRef = await Test.createTestingModule({
|
|
737
|
-
imports: [IdempotencyModule.register()],
|
|
738
|
-
controllers: [FastifyTestController],
|
|
739
|
-
providers: [{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor }],
|
|
740
|
-
}).compile();
|
|
741
|
-
app = moduleRef.createNestApplication<NestFastifyApplication>(new FastifyAdapter());
|
|
742
|
-
await app.init();
|
|
743
|
-
await app.getHttpAdapter().getInstance().ready();
|
|
744
|
-
});
|
|
745
|
-
|
|
746
|
-
afterAll(async () => { await app?.close(); });
|
|
747
|
-
|
|
748
|
-
it('AC-38: Fastify — two sequential requests with same key invoke handler once and return identical 200 body', async () => {
|
|
749
|
-
const first = await app.inject({
|
|
750
|
-
method: 'POST',
|
|
751
|
-
url: '/test',
|
|
752
|
-
headers: { 'idempotency-key': 'K5', 'content-type': 'application/json' },
|
|
753
|
-
payload: { a: 1 },
|
|
754
|
-
});
|
|
755
|
-
const second = await app.inject({
|
|
756
|
-
method: 'POST',
|
|
757
|
-
url: '/test',
|
|
758
|
-
headers: { 'idempotency-key': 'K5', 'content-type': 'application/json' },
|
|
759
|
-
payload: { a: 1 },
|
|
760
|
-
});
|
|
761
|
-
expect(first.statusCode).toBe(200);
|
|
762
|
-
expect(second.statusCode).toBe(200);
|
|
763
|
-
expect(JSON.parse(second.body)).toEqual(JSON.parse(first.body));
|
|
764
|
-
expect(_fastifyHandlerCount).toBe(1);
|
|
765
|
-
});
|
|
766
|
-
});
|