@nathapp/nestjs-idempotency 4.0.0 → 4.0.1
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/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,439 +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
|
-
HttpStatus,
|
|
10
|
-
} from '@nestjs/common';
|
|
11
|
-
import { Test } from '@nestjs/testing';
|
|
12
|
-
import { Reflector, HttpAdapterHost } from '@nestjs/core';
|
|
13
|
-
import { CallHandler, ExecutionContext } from '@nestjs/common';
|
|
14
|
-
import { createHash } from 'crypto';
|
|
15
|
-
|
|
16
|
-
import {
|
|
17
|
-
computeFingerprint,
|
|
18
|
-
resolveIdempotencyOptions,
|
|
19
|
-
InMemoryIdempotencyStore,
|
|
20
|
-
Idempotent,
|
|
21
|
-
IdempotencyModule,
|
|
22
|
-
IdempotencyInterceptor,
|
|
23
|
-
IdempotencyExceptionCode,
|
|
24
|
-
} from '../../../lib';
|
|
25
|
-
|
|
26
|
-
// ─── Shared test helpers ──────────────────────────────────────────────────────
|
|
27
|
-
|
|
28
|
-
const sha256 = (s: string) => createHash('sha256').update(s).digest('hex');
|
|
29
|
-
|
|
30
|
-
const makeIdempotentReflector = (hasMetadata: boolean): Reflector =>
|
|
31
|
-
({ get: jest.fn().mockReturnValue(hasMetadata ? true : undefined) }) as unknown as Reflector;
|
|
32
|
-
|
|
33
|
-
const makeNext = (body: unknown, isError = false): CallHandler => ({
|
|
34
|
-
handle: jest.fn().mockReturnValue(isError ? throwError(() => body) : of(body)),
|
|
35
|
-
});
|
|
36
|
-
|
|
37
|
-
const makeContext = (opts: {
|
|
38
|
-
method?: string;
|
|
39
|
-
path?: string;
|
|
40
|
-
headers?: Record<string, string>;
|
|
41
|
-
body?: unknown;
|
|
42
|
-
statusCode?: number;
|
|
43
|
-
responseHeaders?: Record<string, string>;
|
|
44
|
-
handler?: object;
|
|
45
|
-
} = {}): ExecutionContext => {
|
|
46
|
-
const statusContainer = { statusCode: opts.statusCode ?? 200 };
|
|
47
|
-
const request = {
|
|
48
|
-
method: opts.method ?? 'POST',
|
|
49
|
-
path: opts.path ?? '/users',
|
|
50
|
-
url: opts.path ?? '/users',
|
|
51
|
-
headers: opts.headers ?? { 'idempotency-key': 'test-key-123' },
|
|
52
|
-
body: opts.body ?? { a: 1 },
|
|
53
|
-
};
|
|
54
|
-
const response = {
|
|
55
|
-
get statusCode() { return statusContainer.statusCode; },
|
|
56
|
-
set statusCode(v: number) { statusContainer.statusCode = v; },
|
|
57
|
-
getHeaders: () => opts.responseHeaders ?? { 'content-type': 'application/json' },
|
|
58
|
-
};
|
|
59
|
-
return {
|
|
60
|
-
getHandler: () => opts.handler ?? {},
|
|
61
|
-
switchToHttp: () => ({ getRequest: () => request, getResponse: () => response }),
|
|
62
|
-
} as unknown as ExecutionContext;
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
const makeStoreMock = (putResult: any = undefined) => ({
|
|
66
|
-
putIfAbsent: jest.fn().mockResolvedValue(putResult),
|
|
67
|
-
complete: jest.fn().mockResolvedValue(undefined),
|
|
68
|
-
remove: jest.fn().mockResolvedValue(undefined),
|
|
69
|
-
get: jest.fn().mockResolvedValue(undefined),
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
const makeHttpAdapterComponents = () => {
|
|
73
|
-
const httpAdapter = { reply: jest.fn(), setHeader: jest.fn() };
|
|
74
|
-
const host = { httpAdapter } as unknown as HttpAdapterHost;
|
|
75
|
-
return { httpAdapter, host };
|
|
76
|
-
};
|
|
77
|
-
|
|
78
|
-
const defaultOptions = {
|
|
79
|
-
headerName: 'Idempotency-Key',
|
|
80
|
-
ttlMs: 86_400_000,
|
|
81
|
-
requireKey: false,
|
|
82
|
-
replayHeaders: ['content-type'],
|
|
83
|
-
};
|
|
84
|
-
|
|
85
|
-
const buildInterceptor = (opts: {
|
|
86
|
-
hasMetadata?: boolean;
|
|
87
|
-
store?: ReturnType<typeof makeStoreMock>;
|
|
88
|
-
requireKey?: boolean;
|
|
89
|
-
replayHeaders?: string[];
|
|
90
|
-
httpAdapterHost?: HttpAdapterHost;
|
|
91
|
-
} = {}) => {
|
|
92
|
-
const reflector = makeIdempotentReflector(opts.hasMetadata ?? true);
|
|
93
|
-
const store = opts.store ?? makeStoreMock();
|
|
94
|
-
const { host } = makeHttpAdapterComponents();
|
|
95
|
-
const adapterHost = opts.httpAdapterHost ?? host;
|
|
96
|
-
const options = {
|
|
97
|
-
...defaultOptions,
|
|
98
|
-
requireKey: opts.requireKey ?? false,
|
|
99
|
-
replayHeaders: opts.replayHeaders ?? defaultOptions.replayHeaders,
|
|
100
|
-
};
|
|
101
|
-
return {
|
|
102
|
-
interceptor: new IdempotencyInterceptor(reflector, store as any, adapterHost, options),
|
|
103
|
-
store,
|
|
104
|
-
adapterHost,
|
|
105
|
-
};
|
|
106
|
-
};
|
|
107
|
-
|
|
108
|
-
const runIntercept = async (
|
|
109
|
-
interceptor: InstanceType<typeof IdempotencyInterceptor>,
|
|
110
|
-
context: ExecutionContext,
|
|
111
|
-
next: CallHandler,
|
|
112
|
-
): Promise<unknown> => {
|
|
113
|
-
let obs: any;
|
|
114
|
-
try {
|
|
115
|
-
obs = interceptor.intercept(context, next);
|
|
116
|
-
} catch (err) {
|
|
117
|
-
throw err;
|
|
118
|
-
}
|
|
119
|
-
if (obs && typeof obs.subscribe === 'function') {
|
|
120
|
-
return lastValueFrom(obs, { defaultValue: undefined });
|
|
121
|
-
}
|
|
122
|
-
return undefined;
|
|
123
|
-
};
|
|
124
|
-
|
|
125
|
-
const captureInterceptError = async (
|
|
126
|
-
interceptor: InstanceType<typeof IdempotencyInterceptor>,
|
|
127
|
-
context: ExecutionContext,
|
|
128
|
-
next: CallHandler,
|
|
129
|
-
): Promise<any> => {
|
|
130
|
-
try {
|
|
131
|
-
await runIntercept(interceptor, context, next);
|
|
132
|
-
} catch (err) {
|
|
133
|
-
return err;
|
|
134
|
-
}
|
|
135
|
-
throw new Error('Expected interceptor to throw but it did not');
|
|
136
|
-
};
|
|
137
|
-
|
|
138
|
-
// ─── Integration controllers ──────────────────────────────────────────────────
|
|
139
|
-
|
|
140
|
-
let _requireKeyHandlerCount = 0;
|
|
141
|
-
|
|
142
|
-
@Controller()
|
|
143
|
-
class RequireKeyTestController {
|
|
144
|
-
@Post('test')
|
|
145
|
-
@Idempotent()
|
|
146
|
-
handle(@Body() _body: unknown) {
|
|
147
|
-
_requireKeyHandlerCount++;
|
|
148
|
-
return { ok: true };
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
let _replayHeaderHandlerCount = 0;
|
|
153
|
-
|
|
154
|
-
@Controller()
|
|
155
|
-
class ReplayHeaderTestController {
|
|
156
|
-
@Post('test')
|
|
157
|
-
@Idempotent()
|
|
158
|
-
handle(@Body() _body: unknown) {
|
|
159
|
-
_replayHeaderHandlerCount++;
|
|
160
|
-
return { ok: true };
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
165
|
-
// Acceptance Criteria
|
|
166
|
-
// ═══════════════════════════════════════════════════════════════════════════════
|
|
167
|
-
|
|
168
|
-
describe('nestjs-idempotency acceptance criteria', () => {
|
|
169
|
-
|
|
170
|
-
// ── AC-1 ────────────────────────────────────────────────────────────────────
|
|
171
|
-
it('AC-1: computeFingerprint returns same 64-char hex digest for structurally equivalent nested objects with different key orders', () => {
|
|
172
|
-
const A = { nested1: { z: 1, y: 2 }, nested2: { w: 3, v: 4 } };
|
|
173
|
-
const B = { nested2: { v: 4, w: 3 }, nested1: { y: 2, z: 1 } };
|
|
174
|
-
|
|
175
|
-
const digestA = computeFingerprint(A);
|
|
176
|
-
const digestB = computeFingerprint(B);
|
|
177
|
-
|
|
178
|
-
expect(digestA).toMatch(/^[a-f0-9]{64}$/);
|
|
179
|
-
expect(digestB).toMatch(/^[a-f0-9]{64}$/);
|
|
180
|
-
expect(digestA).toBe(digestB);
|
|
181
|
-
});
|
|
182
|
-
|
|
183
|
-
// ── AC-2 ────────────────────────────────────────────────────────────────────
|
|
184
|
-
it('AC-2: resolveIdempotencyOptions preserves replayHeaders order, case, and duplicates without deduplication', () => {
|
|
185
|
-
const input = ['Content-Type', 'X-Custom-Header', 'Content-Type'];
|
|
186
|
-
const resolved = resolveIdempotencyOptions({ replayHeaders: input });
|
|
187
|
-
|
|
188
|
-
// Length: not deduplicated
|
|
189
|
-
expect(resolved.replayHeaders).toHaveLength(3);
|
|
190
|
-
|
|
191
|
-
// Order and case preserved
|
|
192
|
-
expect(resolved.replayHeaders[0]).toBe('Content-Type');
|
|
193
|
-
expect(resolved.replayHeaders[1]).toBe('X-Custom-Header');
|
|
194
|
-
expect(resolved.replayHeaders[2]).toBe('Content-Type');
|
|
195
|
-
});
|
|
196
|
-
|
|
197
|
-
// ── AC-3 ────────────────────────────────────────────────────────────────────
|
|
198
|
-
it('AC-3: complete with non-existent key resolves without error; subsequent get returns undefined; internal Map unchanged', async () => {
|
|
199
|
-
const store = new InMemoryIdempotencyStore({ ttlMs: 86_400_000 });
|
|
200
|
-
const nonExistentKey = 'key-that-was-never-put';
|
|
201
|
-
|
|
202
|
-
// complete on a key that was never inserted resolves (no throw)
|
|
203
|
-
await expect(
|
|
204
|
-
store.complete(nonExistentKey, { status: 200, body: { ok: true }, headers: {} }),
|
|
205
|
-
).resolves.toBeUndefined();
|
|
206
|
-
|
|
207
|
-
// get returns undefined — key not present
|
|
208
|
-
const result = await store.get(nonExistentKey);
|
|
209
|
-
expect(result).toBeUndefined();
|
|
210
|
-
|
|
211
|
-
// Internal Map must not contain the key (phantom entry would block putIfAbsent)
|
|
212
|
-
const internalMap: Map<string, any> = (store as any).map;
|
|
213
|
-
expect(internalMap.has(nonExistentKey)).toBe(false);
|
|
214
|
-
});
|
|
215
|
-
|
|
216
|
-
// ── AC-4 ────────────────────────────────────────────────────────────────────
|
|
217
|
-
it('AC-4: non-2xx handler response causes store.remove called once with storageKey and store.complete never called', async () => {
|
|
218
|
-
const method = 'POST';
|
|
219
|
-
const path = '/orders';
|
|
220
|
-
const idempotencyKey = 'idem-key-ac4';
|
|
221
|
-
const expectedStorageKey = sha256(`${method}\n${path}\n${idempotencyKey}`);
|
|
222
|
-
|
|
223
|
-
const store = makeStoreMock(undefined);
|
|
224
|
-
const { interceptor } = buildInterceptor({ hasMetadata: true, store });
|
|
225
|
-
|
|
226
|
-
const responseBody = { error: 'bad request' };
|
|
227
|
-
const next = makeNext(responseBody);
|
|
228
|
-
const context = makeContext({
|
|
229
|
-
method,
|
|
230
|
-
path,
|
|
231
|
-
headers: { 'idempotency-key': idempotencyKey },
|
|
232
|
-
body: { data: 1 },
|
|
233
|
-
statusCode: 400,
|
|
234
|
-
});
|
|
235
|
-
|
|
236
|
-
const result = await runIntercept(interceptor, context, next);
|
|
237
|
-
|
|
238
|
-
// store.remove called exactly once with the computed storageKey
|
|
239
|
-
expect(store.remove).toHaveBeenCalledTimes(1);
|
|
240
|
-
expect((store.remove as jest.Mock).mock.calls[0][0]).toBe(expectedStorageKey);
|
|
241
|
-
|
|
242
|
-
// store.complete never called — non-2xx not cached
|
|
243
|
-
expect(store.complete).not.toHaveBeenCalled();
|
|
244
|
-
|
|
245
|
-
// Interceptor returns the original response body
|
|
246
|
-
expect(result).toEqual(responseBody);
|
|
247
|
-
});
|
|
248
|
-
|
|
249
|
-
// ── AC-5 ────────────────────────────────────────────────────────────────────
|
|
250
|
-
it('AC-5: store errors propagate; next.handle() is never called more than once; request is not retried', async () => {
|
|
251
|
-
class StoreError extends Error {
|
|
252
|
-
constructor() { super('store failure'); }
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
// Case A: putIfAbsent throws → next.handle() must NOT be called
|
|
256
|
-
{
|
|
257
|
-
const store = {
|
|
258
|
-
putIfAbsent: jest.fn().mockRejectedValue(new StoreError()),
|
|
259
|
-
complete: jest.fn().mockResolvedValue(undefined),
|
|
260
|
-
remove: jest.fn().mockResolvedValue(undefined),
|
|
261
|
-
get: jest.fn().mockResolvedValue(undefined),
|
|
262
|
-
};
|
|
263
|
-
const { host } = makeHttpAdapterComponents();
|
|
264
|
-
const reflector = makeIdempotentReflector(true);
|
|
265
|
-
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, defaultOptions);
|
|
266
|
-
const next = makeNext({ body: 'ok' });
|
|
267
|
-
|
|
268
|
-
const err = await captureInterceptError(interceptor, makeContext(), next);
|
|
269
|
-
|
|
270
|
-
expect(err).toBeInstanceOf(StoreError);
|
|
271
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(0);
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
// Case B: store.complete throws after 2xx → error propagates; next.handle() called exactly once
|
|
275
|
-
{
|
|
276
|
-
const store = {
|
|
277
|
-
putIfAbsent: jest.fn().mockResolvedValue(undefined),
|
|
278
|
-
complete: jest.fn().mockRejectedValue(new StoreError()),
|
|
279
|
-
remove: jest.fn().mockResolvedValue(undefined),
|
|
280
|
-
get: jest.fn().mockResolvedValue(undefined),
|
|
281
|
-
};
|
|
282
|
-
const { host } = makeHttpAdapterComponents();
|
|
283
|
-
const reflector = makeIdempotentReflector(true);
|
|
284
|
-
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, defaultOptions);
|
|
285
|
-
const next = makeNext({ ok: true });
|
|
286
|
-
|
|
287
|
-
const err = await captureInterceptError(interceptor, makeContext({ statusCode: 200 }), next);
|
|
288
|
-
|
|
289
|
-
expect(err).toBeInstanceOf(StoreError);
|
|
290
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(1);
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
// Case C: store.remove throws on non-2xx path → error propagates; next.handle() not retried
|
|
294
|
-
{
|
|
295
|
-
const store = {
|
|
296
|
-
putIfAbsent: jest.fn().mockResolvedValue(undefined),
|
|
297
|
-
complete: jest.fn().mockResolvedValue(undefined),
|
|
298
|
-
remove: jest.fn().mockRejectedValue(new StoreError()),
|
|
299
|
-
get: jest.fn().mockResolvedValue(undefined),
|
|
300
|
-
};
|
|
301
|
-
const { host } = makeHttpAdapterComponents();
|
|
302
|
-
const reflector = makeIdempotentReflector(true);
|
|
303
|
-
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, defaultOptions);
|
|
304
|
-
const next = makeNext({ error: 'fail' });
|
|
305
|
-
|
|
306
|
-
const err = await captureInterceptError(interceptor, makeContext({ statusCode: 500 }), next);
|
|
307
|
-
|
|
308
|
-
expect(err).toBeDefined();
|
|
309
|
-
// next.handle() called once — handler was not retried
|
|
310
|
-
expect((next.handle as jest.Mock).mock.calls).toHaveLength(1);
|
|
311
|
-
}
|
|
312
|
-
});
|
|
313
|
-
|
|
314
|
-
// ── AC-6 ────────────────────────────────────────────────────────────────────
|
|
315
|
-
it('AC-6: replay only sets replayHeaders on adapter response; unrequested stored headers are excluded', async () => {
|
|
316
|
-
const storedResponse = {
|
|
317
|
-
status: 200,
|
|
318
|
-
body: { id: 1 },
|
|
319
|
-
headers: {
|
|
320
|
-
'content-type': 'application/json',
|
|
321
|
-
'content-length': '42',
|
|
322
|
-
'x-custom': 'value',
|
|
323
|
-
},
|
|
324
|
-
};
|
|
325
|
-
const completedRecord = {
|
|
326
|
-
state: 'completed' as const,
|
|
327
|
-
fingerprint: computeFingerprint({ a: 1 }),
|
|
328
|
-
createdAt: Date.now(),
|
|
329
|
-
response: storedResponse,
|
|
330
|
-
};
|
|
331
|
-
|
|
332
|
-
const store = makeStoreMock(completedRecord);
|
|
333
|
-
const { httpAdapter, host } = makeHttpAdapterComponents();
|
|
334
|
-
const reflector = makeIdempotentReflector(true);
|
|
335
|
-
// replayHeaders contains only 'content-type'
|
|
336
|
-
const options = { ...defaultOptions, replayHeaders: ['content-type'] };
|
|
337
|
-
const interceptor = new IdempotencyInterceptor(reflector, store as any, host, options);
|
|
338
|
-
|
|
339
|
-
await runIntercept(interceptor, makeContext(), makeNext('ignored'));
|
|
340
|
-
|
|
341
|
-
// adapter.reply must have been called once
|
|
342
|
-
expect(httpAdapter.reply).toHaveBeenCalledTimes(1);
|
|
343
|
-
|
|
344
|
-
// Collect all header names passed to setHeader
|
|
345
|
-
const setHeaderCalls: Array<[unknown, string, unknown]> = (httpAdapter.setHeader as jest.Mock).mock.calls as any;
|
|
346
|
-
const passedHeaderNames = setHeaderCalls.map(([, name]) => name.toLowerCase());
|
|
347
|
-
|
|
348
|
-
// Only 'content-type' should be forwarded
|
|
349
|
-
expect(passedHeaderNames).toContain('content-type');
|
|
350
|
-
|
|
351
|
-
// 'content-length' and 'x-custom' must NOT be set on the adapter response
|
|
352
|
-
expect(passedHeaderNames).not.toContain('content-length');
|
|
353
|
-
expect(passedHeaderNames).not.toContain('x-custom');
|
|
354
|
-
});
|
|
355
|
-
|
|
356
|
-
// ── AC-7 (integration-check) ─────────────────────────────────────────────────
|
|
357
|
-
describe('AC-7: requireKey=true returns HTTP 400 with IDEMPOTENCY_KEY_REQUIRED error when Idempotency-Key header is absent', () => {
|
|
358
|
-
let app: INestApplication;
|
|
359
|
-
|
|
360
|
-
beforeAll(async () => {
|
|
361
|
-
_requireKeyHandlerCount = 0;
|
|
362
|
-
const moduleRef = await Test.createTestingModule({
|
|
363
|
-
imports: [IdempotencyModule.register({ requireKey: true })],
|
|
364
|
-
controllers: [RequireKeyTestController],
|
|
365
|
-
providers: [{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor }],
|
|
366
|
-
}).compile();
|
|
367
|
-
app = moduleRef.createNestApplication();
|
|
368
|
-
await app.init();
|
|
369
|
-
});
|
|
370
|
-
|
|
371
|
-
afterAll(async () => { await app?.close(); });
|
|
372
|
-
|
|
373
|
-
it('returns HTTP 400 and error body with MISSING_REQUIRED_KEY code when key header is absent', async () => {
|
|
374
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
375
|
-
const supertest = require('supertest');
|
|
376
|
-
|
|
377
|
-
const res = await supertest(app.getHttpServer())
|
|
378
|
-
.post('/test')
|
|
379
|
-
.send({ a: 1 });
|
|
380
|
-
|
|
381
|
-
expect(res.statusCode).toBe(HttpStatus.BAD_REQUEST);
|
|
382
|
-
|
|
383
|
-
// AppException response body shape: { code, args, prefix }
|
|
384
|
-
const body = typeof res.body === 'string' ? JSON.parse(res.body) : res.body;
|
|
385
|
-
expect(body).toBeDefined();
|
|
386
|
-
expect(body.code).toBe(IdempotencyExceptionCode.MISSING_REQUIRED_KEY);
|
|
387
|
-
|
|
388
|
-
// Handler must NOT have been invoked
|
|
389
|
-
expect(_requireKeyHandlerCount).toBe(0);
|
|
390
|
-
});
|
|
391
|
-
});
|
|
392
|
-
|
|
393
|
-
// ── AC-8 (integration-check) ─────────────────────────────────────────────────
|
|
394
|
-
describe('AC-8: replay response contains only replayHeaders entries; location and x-custom are excluded', () => {
|
|
395
|
-
let app: INestApplication;
|
|
396
|
-
|
|
397
|
-
beforeAll(async () => {
|
|
398
|
-
_replayHeaderHandlerCount = 0;
|
|
399
|
-
const moduleRef = await Test.createTestingModule({
|
|
400
|
-
imports: [IdempotencyModule.register({ replayHeaders: ['content-type'] })],
|
|
401
|
-
controllers: [ReplayHeaderTestController],
|
|
402
|
-
providers: [{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor }],
|
|
403
|
-
}).compile();
|
|
404
|
-
app = moduleRef.createNestApplication();
|
|
405
|
-
await app.init();
|
|
406
|
-
});
|
|
407
|
-
|
|
408
|
-
afterAll(async () => { await app?.close(); });
|
|
409
|
-
|
|
410
|
-
it('replay response has content-type but not location or x-custom', async () => {
|
|
411
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
412
|
-
const supertest = require('supertest');
|
|
413
|
-
const idempotencyKey = 'AC8-replay-' + Date.now();
|
|
414
|
-
|
|
415
|
-
// First request — handler runs, response cached
|
|
416
|
-
const first = await supertest(app.getHttpServer())
|
|
417
|
-
.post('/test')
|
|
418
|
-
.set('Idempotency-Key', idempotencyKey)
|
|
419
|
-
.send({ data: 'ac8' });
|
|
420
|
-
expect(first.statusCode).toBe(200);
|
|
421
|
-
expect(_replayHeaderHandlerCount).toBe(1);
|
|
422
|
-
|
|
423
|
-
// Second request — must be a replay (handler not called again)
|
|
424
|
-
const second = await supertest(app.getHttpServer())
|
|
425
|
-
.post('/test')
|
|
426
|
-
.set('Idempotency-Key', idempotencyKey)
|
|
427
|
-
.send({ data: 'ac8' });
|
|
428
|
-
expect(second.statusCode).toBe(200);
|
|
429
|
-
expect(_replayHeaderHandlerCount).toBe(1);
|
|
430
|
-
|
|
431
|
-
// 'content-type' is in replayHeaders — must be present
|
|
432
|
-
expect(second.headers['content-type']).toBeDefined();
|
|
433
|
-
|
|
434
|
-
// 'location' and 'x-custom' are NOT in replayHeaders — must be absent
|
|
435
|
-
expect(second.headers['location']).toBeUndefined();
|
|
436
|
-
expect(second.headers['x-custom']).toBeUndefined();
|
|
437
|
-
});
|
|
438
|
-
});
|
|
439
|
-
});
|
package/.nax/test-debug.ts
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
// Test the controller instantiation
|
|
2
|
-
import 'reflect-metadata';
|
|
3
|
-
import { Controller, Post, Body } from '@nestjs/common';
|
|
4
|
-
import { Idempotent } from '../../../lib/decorator/idempotent.decorator';
|
|
5
|
-
|
|
6
|
-
@Controller()
|
|
7
|
-
class TestController {
|
|
8
|
-
@Post('test')
|
|
9
|
-
@Idempotent()
|
|
10
|
-
async handle(@Body() _body: unknown) {
|
|
11
|
-
return { ok: true };
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
describe('Controller instantiation', () => {
|
|
16
|
-
it('should be a constructor', () => {
|
|
17
|
-
console.log('typeof TestController:', typeof TestController);
|
|
18
|
-
console.log('TestController.prototype:', typeof TestController.prototype);
|
|
19
|
-
expect(typeof TestController).toBe('function');
|
|
20
|
-
expect(() => new TestController()).not.toThrow();
|
|
21
|
-
});
|
|
22
|
-
});
|
package/.turbo/turbo-build.log
DELETED
package/CHANGELOG.md
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
# @nathapp/nestjs-idempotency
|
|
2
|
-
|
|
3
|
-
## 4.0.0
|
|
4
|
-
|
|
5
|
-
### Major Changes
|
|
6
|
-
|
|
7
|
-
- 2319e9d: BREAKING: drop NestJS 8/9 peer ranges and require Node ^20.19.0 || >=22.12.0. Support NestJS 12. Peer ranges now cover NestJS 10, 11 and 12 (Node ^20.19.0 || >=22.12.0 is required because NestJS 12 is ESM-only). The configurable module builder no longer deep-imports a directory that is unresolvable on NestJS 12, and TwoFactorGuard / TwoFactorForceGuard redeclare their constructor DI metadata because NestJS 12 no longer inherits @Optional() from base classes.
|
|
8
|
-
|
|
9
|
-
Other consumer-facing changes:
|
|
10
|
-
|
|
11
|
-
- `@nathapp/nestjs-health`: `@nestjs/terminus` moved from `dependencies` to `peerDependencies` (`^11.0.0 || ^12.0.0`) so NestJS 12 apps can use terminus 12. Install `@nestjs/terminus` in your app.
|
|
12
|
-
- Optional-package loading (`loadPackage`) now throws a descriptive `Error` (original error on `cause`) instead of logging and calling `process.exit(1)` when an optional package is missing.
|
|
13
|
-
|
|
14
|
-
## 4.0.0-rc.0
|
|
15
|
-
|
|
16
|
-
### Major Changes
|
|
17
|
-
|
|
18
|
-
- c3aeb46: BREAKING: drop NestJS 8/9 peer ranges and require Node ^20.19.0 || >=22.12.0. Support NestJS 12. Peer ranges now cover NestJS 10, 11 and 12 (Node ^20.19.0 || >=22.12.0 is required because NestJS 12 is ESM-only). The configurable module builder no longer deep-imports a directory that is unresolvable on NestJS 12, and TwoFactorGuard / TwoFactorForceGuard redeclare their constructor DI metadata because NestJS 12 no longer inherits @Optional() from base classes.
|
|
19
|
-
|
|
20
|
-
Other consumer-facing changes:
|
|
21
|
-
|
|
22
|
-
- `@nathapp/nestjs-health`: `@nestjs/terminus` moved from `dependencies` to `peerDependencies` (`^11.0.0 || ^12.0.0`) so NestJS 12 apps can use terminus 12. Install `@nestjs/terminus` in your app.
|
|
23
|
-
- Optional-package loading (`loadPackage`) now throws a descriptive `Error` (original error on `cause`) instead of logging and calling `process.exit(1)` when an optional package is missing.
|
|
24
|
-
|
|
25
|
-
### Patch Changes
|
|
26
|
-
|
|
27
|
-
- Updated dependencies [c3aeb46]
|
|
28
|
-
- @nathapp/nestjs-common@4.0.0-rc.0
|
|
29
|
-
|
|
30
|
-
## 3.3.0
|
|
31
|
-
|
|
32
|
-
### Minor Changes
|
|
33
|
-
|
|
34
|
-
- a27440f: 3.3.0 milestone release. The `@nathapp/nestjs-*` packages now version and publish in lockstep at a unified version.
|
|
35
|
-
|
|
36
|
-
- **nestjs-csrf**: first public release — stateless double-submit-cookie CSRF guard (zero-dep HMAC, Express + Fastify, Bearer coexist skip, `@SkipCsrf()`, auto-binds `APP_GUARD`).
|
|
37
|
-
- **nestjs-health**: first public release — terminus aggregator over cache/prisma/queue with k8s liveness/readiness probes via a dynamic controller factory.
|
|
38
|
-
- **nestjs-idempotency**: first public release — `@Idempotent()` interceptor (zero-dep sha256 fingerprint, Express + Fastify, 409-in-flight, 2xx replay, fingerprint mismatch 422, fail-closed on store error).
|
|
39
|
-
- **nestjs-observability**: first public release — Prometheus RED metrics + OpenTelemetry tracing joined to the logging ALS; `initTracing()` pre-bootstrap hook.
|
|
40
|
-
- **nestjs-outbox**: first public release — transactional outbox relay (at-least-once via `ITransactionManager`, lease-claim + backoff, dead-letter).
|
|
41
|
-
- **nestjs-storage**: migrated from aws-sdk v2 to v3 (zero runtime dep via `import type` + lazy `loadPackage`); NFSStorage stub replaced with an S3-style HTTP file-service client.
|
|
42
|
-
- **nestjs-cache**: `delByPattern` now routes through Redis SCAN instead of an O(n) key sweep, with glob-detection and multi-tier iterator support.
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
export const IDEMPOTENCY_STORE = Symbol.for('IDEMPOTENCY_STORE');
|
|
2
|
-
export const IDEMPOTENCY_MODULE_OPTIONS = 'IDEMPOTENCY_MODULE_OPTIONS';
|
|
3
|
-
export const IDEMPOTENCY_INTERCEPTOR_OPTIONS = 'IDEMPOTENCY_INTERCEPTOR_OPTIONS';
|
|
4
|
-
export const IDEMPOTENT_METADATA_KEY = 'idempotent';
|
|
5
|
-
export const DEFAULT_HEADER_NAME = 'Idempotency-Key';
|
|
6
|
-
export const DEFAULT_TTL_MS = 86_400_000;
|
|
7
|
-
export const DEFAULT_REQUIRE_KEY = false;
|
|
8
|
-
export const DEFAULT_REPLAY_HEADERS = ['content-type'];
|
package/lib/constant/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './idempotency.constants';
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { HttpStatus } from '@nestjs/common';
|
|
2
|
-
import { AppException } from '@nathapp/nestjs-common';
|
|
3
|
-
import { IdempotencyExceptionCode } from './idempotency-exception-code.enum';
|
|
4
|
-
|
|
5
|
-
export class IdempotencyConflictException extends AppException {
|
|
6
|
-
constructor() {
|
|
7
|
-
super(IdempotencyExceptionCode.CONFLICT_IN_FLIGHT, undefined, undefined, HttpStatus.CONFLICT);
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
export class IdempotencyKeyReuseException extends AppException {
|
|
12
|
-
constructor() {
|
|
13
|
-
super(IdempotencyExceptionCode.KEY_REUSE_MISMATCH, undefined, undefined, HttpStatus.UNPROCESSABLE_ENTITY);
|
|
14
|
-
}
|
|
15
|
-
}
|
package/lib/index.ts
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
export * from './constant/idempotency.constants';
|
|
2
|
-
export * from './decorator/idempotent.decorator';
|
|
3
|
-
export * from './exception/idempotency-exception-code.enum';
|
|
4
|
-
export * from './exception/idempotency.exceptions';
|
|
5
|
-
export * from './interceptor/idempotency.interceptor';
|
|
6
|
-
export * from './interface/idempotency-module-options.interface';
|
|
7
|
-
export * from './interface/idempotency-record.interface';
|
|
8
|
-
export * from './interface/idempotency-store.interface';
|
|
9
|
-
export * from './module/idempotency.module';
|
|
10
|
-
export * from './provider/default-principal-extractor';
|
|
11
|
-
export * from './provider/fingerprint';
|
|
12
|
-
export * from './provider/in-memory-idempotency-store';
|
|
13
|
-
export * from './provider/resolve-idempotency-options';
|