@nathapp/nestjs-idempotency 3.3.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 +10 -10
- 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 -15
- 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,187 +0,0 @@
|
|
|
1
|
-
import { Inject, Injectable, Logger, NestInterceptor, ExecutionContext, CallHandler, HttpStatus } from '@nestjs/common';
|
|
2
|
-
import { Observable, from, of, throwError } from 'rxjs';
|
|
3
|
-
import { switchMap, map, catchError } from 'rxjs/operators';
|
|
4
|
-
import { createHash } from 'crypto';
|
|
5
|
-
import { Reflector, HttpAdapterHost } from '@nestjs/core';
|
|
6
|
-
import { AppException } from '@nathapp/nestjs-common';
|
|
7
|
-
import { IIdempotencyStore } from '../interface/idempotency-store.interface';
|
|
8
|
-
import { InterceptorOptions } from '../provider/resolve-idempotency-options';
|
|
9
|
-
import {
|
|
10
|
-
IDEMPOTENCY_INTERCEPTOR_OPTIONS,
|
|
11
|
-
IDEMPOTENT_METADATA_KEY,
|
|
12
|
-
IDEMPOTENCY_STORE,
|
|
13
|
-
} from '../constant/idempotency.constants';
|
|
14
|
-
import { computeFingerprint } from '../provider/fingerprint';
|
|
15
|
-
import { IdempotencyConflictException } from '../exception/idempotency.exceptions';
|
|
16
|
-
import { IdempotencyKeyReuseException } from '../exception/idempotency.exceptions';
|
|
17
|
-
import { IdempotencyExceptionCode } from '../exception/idempotency-exception-code.enum';
|
|
18
|
-
|
|
19
|
-
@Injectable()
|
|
20
|
-
export class IdempotencyInterceptor implements NestInterceptor {
|
|
21
|
-
private readonly _logger = new Logger(IdempotencyInterceptor.name);
|
|
22
|
-
|
|
23
|
-
constructor(
|
|
24
|
-
private readonly _reflector: Reflector,
|
|
25
|
-
@Inject(IDEMPOTENCY_STORE) private readonly _store: IIdempotencyStore,
|
|
26
|
-
private readonly _httpAdapterHost: HttpAdapterHost,
|
|
27
|
-
@Inject(IDEMPOTENCY_INTERCEPTOR_OPTIONS) private readonly _options: InterceptorOptions,
|
|
28
|
-
) {}
|
|
29
|
-
|
|
30
|
-
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
31
|
-
const hasMetadata = this._reflector.get<boolean>(IDEMPOTENT_METADATA_KEY, context.getHandler());
|
|
32
|
-
if (!hasMetadata) {
|
|
33
|
-
return next.handle();
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
// Idempotency replay is meaningless outside HTTP (response caching/replay via
|
|
37
|
-
// switchToHttp() has no rpc/ws equivalent here). Skip cleanly rather than
|
|
38
|
-
// mis-dispatch against the wrong transport's context.
|
|
39
|
-
if (context.getType() !== 'http') {
|
|
40
|
-
return next.handle();
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
const response = context.switchToHttp().getResponse<{
|
|
44
|
-
statusCode?: number;
|
|
45
|
-
}>();
|
|
46
|
-
|
|
47
|
-
// Normalize NestJS/Express default POST status (201 Created) to 200 OK for
|
|
48
|
-
// idempotent endpoints. Idempotent endpoints do not necessarily create new
|
|
49
|
-
// resources on each call — they may simply return the previously-cached
|
|
50
|
-
// response — so 200 is the semantically appropriate default.
|
|
51
|
-
if (response.statusCode === HttpStatus.CREATED) {
|
|
52
|
-
response.statusCode = HttpStatus.OK;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
const request = context.switchToHttp().getRequest<{
|
|
56
|
-
method: string;
|
|
57
|
-
path?: string;
|
|
58
|
-
url?: string;
|
|
59
|
-
headers: Record<string, string | string[]>;
|
|
60
|
-
body: unknown;
|
|
61
|
-
user?: unknown;
|
|
62
|
-
}>();
|
|
63
|
-
|
|
64
|
-
const headerName = this._options.headerName.toLowerCase();
|
|
65
|
-
const rawKey = request.headers[headerName];
|
|
66
|
-
const key = Array.isArray(rawKey) ? rawKey[0] : rawKey;
|
|
67
|
-
|
|
68
|
-
if (!key) {
|
|
69
|
-
if (this._options.requireKey) {
|
|
70
|
-
throw new AppException(
|
|
71
|
-
IdempotencyExceptionCode.MISSING_REQUIRED_KEY,
|
|
72
|
-
undefined,
|
|
73
|
-
undefined,
|
|
74
|
-
HttpStatus.BAD_REQUEST,
|
|
75
|
-
);
|
|
76
|
-
}
|
|
77
|
-
return next.handle();
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
const routePath = request.path ?? request.url ?? '';
|
|
81
|
-
// Scope the storage key to the authenticated principal (when resolvable) so
|
|
82
|
-
// two different callers cannot collide on the same client-chosen
|
|
83
|
-
// Idempotency-Key and replay each other's cached response. Falls back to
|
|
84
|
-
// unscoped (method + path + key) when no principal is present, e.g. on a
|
|
85
|
-
// genuinely unauthenticated/public route.
|
|
86
|
-
const principal = this._options.principalExtractor(request);
|
|
87
|
-
if (!principal) {
|
|
88
|
-
// Visibility for SEC-1: an unresolved principal means the storage key falls
|
|
89
|
-
// back to the pre-fix unscoped shape (method+path+key), which is only safe
|
|
90
|
-
// for genuinely public/unauthenticated routes. Surface this so a misconfigured
|
|
91
|
-
// principalExtractor (or a missing/misordered auth guard on a route that should
|
|
92
|
-
// require auth) is discoverable in logs rather than silently reproducing the
|
|
93
|
-
// original cross-user-replay bug.
|
|
94
|
-
this._logger.warn(
|
|
95
|
-
`Idempotency key for ${request.method} ${routePath} is unscoped: principalExtractor ` +
|
|
96
|
-
`returned no principal. This is expected for public routes, but may indicate a ` +
|
|
97
|
-
`misconfigured principalExtractor or a missing auth guard.`,
|
|
98
|
-
);
|
|
99
|
-
}
|
|
100
|
-
const keyParts = principal
|
|
101
|
-
? `${request.method}\n${routePath}\n${principal}\n${key}`
|
|
102
|
-
: `${request.method}\n${routePath}\n${key}`;
|
|
103
|
-
const storageKey = createHash('sha256').update(keyParts).digest('hex');
|
|
104
|
-
|
|
105
|
-
const fingerprint = computeFingerprint(request.body);
|
|
106
|
-
|
|
107
|
-
return from(
|
|
108
|
-
this._store.putIfAbsent(storageKey, {
|
|
109
|
-
state: 'pending',
|
|
110
|
-
fingerprint,
|
|
111
|
-
createdAt: Date.now(),
|
|
112
|
-
}),
|
|
113
|
-
).pipe(
|
|
114
|
-
switchMap(existing => {
|
|
115
|
-
if (existing === undefined) {
|
|
116
|
-
return this._executeAndStore(context, next, storageKey);
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
if (existing.fingerprint !== fingerprint) {
|
|
120
|
-
throw new IdempotencyKeyReuseException();
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
if (existing.state === 'pending') {
|
|
124
|
-
throw new IdempotencyConflictException();
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
if (!existing.response) {
|
|
128
|
-
throw new Error('Idempotency store returned a completed record with no cached response');
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
return this._replay(context, existing.response);
|
|
132
|
-
}),
|
|
133
|
-
);
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
private _executeAndStore(
|
|
137
|
-
context: ExecutionContext,
|
|
138
|
-
next: CallHandler,
|
|
139
|
-
storageKey: string,
|
|
140
|
-
): Observable<unknown> {
|
|
141
|
-
const response = context.switchToHttp().getResponse<{
|
|
142
|
-
statusCode: number;
|
|
143
|
-
getHeaders: () => Record<string, string>;
|
|
144
|
-
}>();
|
|
145
|
-
|
|
146
|
-
return next.handle().pipe(
|
|
147
|
-
switchMap(body => {
|
|
148
|
-
const status = response.statusCode;
|
|
149
|
-
if (status >= 200 && status < 300) {
|
|
150
|
-
const allHeaders = response.getHeaders();
|
|
151
|
-
const headers = this._options.replayHeaders.reduce<Record<string, string>>((acc, h) => {
|
|
152
|
-
const v = allHeaders[h.toLowerCase()];
|
|
153
|
-
if (v !== undefined) acc[h.toLowerCase()] = v;
|
|
154
|
-
return acc;
|
|
155
|
-
}, {});
|
|
156
|
-
return from(this._store.complete(storageKey, { status, body, headers })).pipe(map(() => body));
|
|
157
|
-
}
|
|
158
|
-
return from(this._store.remove(storageKey)).pipe(map(() => body));
|
|
159
|
-
}),
|
|
160
|
-
catchError(err =>
|
|
161
|
-
from(this._store.remove(storageKey).catch(() => undefined)).pipe(
|
|
162
|
-
switchMap(() => throwError(() => err)),
|
|
163
|
-
),
|
|
164
|
-
),
|
|
165
|
-
);
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
private _replay(
|
|
169
|
-
context: ExecutionContext,
|
|
170
|
-
storedResponse: NonNullable<import('../interface/idempotency-record.interface').IdempotencyRecord['response']>,
|
|
171
|
-
): Observable<unknown> {
|
|
172
|
-
const rawResponse = context.switchToHttp().getResponse();
|
|
173
|
-
const httpAdapter = this._httpAdapterHost.httpAdapter;
|
|
174
|
-
|
|
175
|
-
// Re-filter against replayHeaders even though _executeAndStore already narrowed
|
|
176
|
-
// at capture time — the store is not a trusted enforcer of this allowlist (a
|
|
177
|
-
// different store implementation, or corrupted state, could return extra headers).
|
|
178
|
-
for (const [header, value] of Object.entries(storedResponse.headers)) {
|
|
179
|
-
if (this._options.replayHeaders.some(h => h.toLowerCase() === header.toLowerCase())) {
|
|
180
|
-
httpAdapter.setHeader(rawResponse, header, value);
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
httpAdapter.reply(rawResponse, storedResponse.body, storedResponse.status);
|
|
184
|
-
|
|
185
|
-
return of(null);
|
|
186
|
-
}
|
|
187
|
-
}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { IIdempotencyStore } from './idempotency-store.interface';
|
|
2
|
-
import { PrincipalExtractor } from '../provider/default-principal-extractor';
|
|
3
|
-
|
|
4
|
-
export interface IdempotencyModuleOptions {
|
|
5
|
-
store?: IIdempotencyStore;
|
|
6
|
-
headerName?: string;
|
|
7
|
-
ttlMs?: number;
|
|
8
|
-
requireKey?: boolean;
|
|
9
|
-
replayHeaders?: string[];
|
|
10
|
-
/**
|
|
11
|
-
* Extracts a stable caller identifier (e.g. `request.user.id`) that is
|
|
12
|
-
* folded into the idempotency storage key so two different callers cannot
|
|
13
|
-
* collide on the same client-chosen `Idempotency-Key` and replay each
|
|
14
|
-
* other's cached response. Defaults to reading `request.user.id` /
|
|
15
|
-
* `request.user.sub`. Returning `undefined` (e.g. on an unauthenticated
|
|
16
|
-
* route) falls back to the previous unscoped key derivation for that
|
|
17
|
-
* request — set this explicitly if that fallback is not acceptable for
|
|
18
|
-
* your routes.
|
|
19
|
-
*/
|
|
20
|
-
principalExtractor?: PrincipalExtractor;
|
|
21
|
-
}
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
export type IdempotencyState = 'pending' | 'completed';
|
|
2
|
-
|
|
3
|
-
export interface StoredResponse {
|
|
4
|
-
status: number;
|
|
5
|
-
body: unknown;
|
|
6
|
-
headers: Record<string, string>;
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export interface IdempotencyRecord {
|
|
10
|
-
state: IdempotencyState;
|
|
11
|
-
fingerprint: string;
|
|
12
|
-
createdAt: number;
|
|
13
|
-
response?: StoredResponse;
|
|
14
|
-
}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { IdempotencyRecord, StoredResponse } from './idempotency-record.interface';
|
|
2
|
-
|
|
3
|
-
export interface IIdempotencyStore {
|
|
4
|
-
putIfAbsent(key: string, record: IdempotencyRecord): Promise<IdempotencyRecord | undefined>;
|
|
5
|
-
complete(key: string, response: StoredResponse): Promise<void>;
|
|
6
|
-
remove(key: string): Promise<void>;
|
|
7
|
-
get(key: string): Promise<IdempotencyRecord | undefined>;
|
|
8
|
-
}
|
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import { DynamicModule, Module } from '@nestjs/common';
|
|
2
|
-
import { ConfigurableModuleClass } from '@nathapp/nestjs-common';
|
|
3
|
-
import { IdempotencyModuleOptions } from '../interface/idempotency-module-options.interface';
|
|
4
|
-
import { IdempotencyInterceptor } from '../interceptor/idempotency.interceptor';
|
|
5
|
-
import {
|
|
6
|
-
DEFAULT_HEADER_NAME,
|
|
7
|
-
DEFAULT_REPLAY_HEADERS,
|
|
8
|
-
DEFAULT_REQUIRE_KEY,
|
|
9
|
-
DEFAULT_TTL_MS,
|
|
10
|
-
IDEMPOTENCY_INTERCEPTOR_OPTIONS,
|
|
11
|
-
IDEMPOTENCY_MODULE_OPTIONS,
|
|
12
|
-
IDEMPOTENCY_STORE,
|
|
13
|
-
} from '../constant/idempotency.constants';
|
|
14
|
-
import { InterceptorOptions, resolveIdempotencyOptions } from '../provider/resolve-idempotency-options';
|
|
15
|
-
import { defaultPrincipalExtractor } from '../provider/default-principal-extractor';
|
|
16
|
-
|
|
17
|
-
type IdempotencyRegisterAsyncOptions = Parameters<
|
|
18
|
-
ReturnType<typeof ConfigurableModuleClass<IdempotencyModuleOptions>>['registerAsync']
|
|
19
|
-
>[0];
|
|
20
|
-
|
|
21
|
-
@Module({
|
|
22
|
-
providers: [
|
|
23
|
-
{
|
|
24
|
-
provide: IDEMPOTENCY_STORE,
|
|
25
|
-
useFactory: (options?: IdempotencyModuleOptions) => resolveIdempotencyOptions(options).store,
|
|
26
|
-
inject: [IDEMPOTENCY_MODULE_OPTIONS],
|
|
27
|
-
},
|
|
28
|
-
{
|
|
29
|
-
provide: IDEMPOTENCY_INTERCEPTOR_OPTIONS,
|
|
30
|
-
useFactory: (options?: IdempotencyModuleOptions): InterceptorOptions => ({
|
|
31
|
-
headerName: options?.headerName ?? DEFAULT_HEADER_NAME,
|
|
32
|
-
ttlMs: options?.ttlMs ?? DEFAULT_TTL_MS,
|
|
33
|
-
requireKey: options?.requireKey ?? DEFAULT_REQUIRE_KEY,
|
|
34
|
-
replayHeaders: options?.replayHeaders ?? DEFAULT_REPLAY_HEADERS,
|
|
35
|
-
principalExtractor: options?.principalExtractor ?? defaultPrincipalExtractor,
|
|
36
|
-
}),
|
|
37
|
-
inject: [IDEMPOTENCY_MODULE_OPTIONS],
|
|
38
|
-
},
|
|
39
|
-
IdempotencyInterceptor,
|
|
40
|
-
],
|
|
41
|
-
exports: [IdempotencyInterceptor, IDEMPOTENCY_STORE, IDEMPOTENCY_INTERCEPTOR_OPTIONS],
|
|
42
|
-
})
|
|
43
|
-
export class IdempotencyModule extends ConfigurableModuleClass<IdempotencyModuleOptions>(
|
|
44
|
-
IDEMPOTENCY_MODULE_OPTIONS,
|
|
45
|
-
) {
|
|
46
|
-
static register(options?: IdempotencyModuleOptions): DynamicModule {
|
|
47
|
-
return {
|
|
48
|
-
...super.register(options ?? ({} as IdempotencyModuleOptions)),
|
|
49
|
-
module: IdempotencyModule,
|
|
50
|
-
global: true,
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
static registerAsync(options: IdempotencyRegisterAsyncOptions): DynamicModule {
|
|
55
|
-
return {
|
|
56
|
-
...super.registerAsync(options),
|
|
57
|
-
module: IdempotencyModule,
|
|
58
|
-
global: true,
|
|
59
|
-
};
|
|
60
|
-
}
|
|
61
|
-
}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Extracts a stable identifier for the authenticated principal from an
|
|
3
|
-
* incoming HTTP request, so the idempotency storage key can be scoped to the
|
|
4
|
-
* caller and not just to `method + path + Idempotency-Key`.
|
|
5
|
-
*
|
|
6
|
-
* Reads `request.user.id` — the location JWT/session auth guards in this
|
|
7
|
-
* monorepo populate (see `@nathapp/nestjs-auth`'s `IPrincipal`). Returns
|
|
8
|
-
* `undefined` when no principal is present (unauthenticated route), in which
|
|
9
|
-
* case the caller falls back to unscoped behavior for that request.
|
|
10
|
-
*/
|
|
11
|
-
export type PrincipalExtractor = (request: unknown) => string | undefined;
|
|
12
|
-
|
|
13
|
-
export const defaultPrincipalExtractor: PrincipalExtractor = (request: unknown): string | undefined => {
|
|
14
|
-
const user = (request as { user?: { id?: string; sub?: string } } | undefined)?.user;
|
|
15
|
-
const id = user?.id ?? user?.sub;
|
|
16
|
-
return typeof id === 'string' && id.length > 0 ? id : undefined;
|
|
17
|
-
};
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { createHash } from 'crypto';
|
|
2
|
-
|
|
3
|
-
function stableStringify(value: unknown): string {
|
|
4
|
-
if (value === null || typeof value !== 'object') {
|
|
5
|
-
return JSON.stringify(value);
|
|
6
|
-
}
|
|
7
|
-
if (Array.isArray(value)) {
|
|
8
|
-
return '[' + value.map(stableStringify).join(',') + ']';
|
|
9
|
-
}
|
|
10
|
-
const sorted = Object.keys(value as object).sort();
|
|
11
|
-
return '{' + sorted.map(k => JSON.stringify(k) + ':' + stableStringify((value as Record<string, unknown>)[k])).join(',') + '}';
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export function computeFingerprint(body: unknown): string {
|
|
15
|
-
const serialized = stableStringify(body === undefined ? null : body);
|
|
16
|
-
return createHash('sha256').update(serialized).digest('hex');
|
|
17
|
-
}
|
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
import { IIdempotencyStore } from '../interface/idempotency-store.interface';
|
|
2
|
-
import { IdempotencyRecord } from '../interface/idempotency-record.interface';
|
|
3
|
-
import { StoredResponse } from '../interface/idempotency-record.interface';
|
|
4
|
-
import { DEFAULT_TTL_MS } from '../constant/idempotency.constants';
|
|
5
|
-
|
|
6
|
-
export class InMemoryIdempotencyStore implements IIdempotencyStore {
|
|
7
|
-
private readonly map = new Map<string, IdempotencyRecord>();
|
|
8
|
-
private readonly ttlMs: number;
|
|
9
|
-
|
|
10
|
-
constructor(opts?: { ttlMs?: number }) {
|
|
11
|
-
this.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
private isExpired(record: IdempotencyRecord): boolean {
|
|
15
|
-
return Date.now() - record.createdAt >= this.ttlMs;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
async putIfAbsent(key: string, record: IdempotencyRecord): Promise<IdempotencyRecord | undefined> {
|
|
19
|
-
const existing = this.map.get(key);
|
|
20
|
-
if (existing !== undefined) {
|
|
21
|
-
if (!this.isExpired(existing)) {
|
|
22
|
-
return { ...existing };
|
|
23
|
-
}
|
|
24
|
-
this.map.delete(key);
|
|
25
|
-
}
|
|
26
|
-
this.map.set(key, record);
|
|
27
|
-
return undefined;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
async complete(key: string, response: StoredResponse): Promise<void> {
|
|
31
|
-
const existing = this.map.get(key);
|
|
32
|
-
if (existing === undefined || this.isExpired(existing)) {
|
|
33
|
-
return;
|
|
34
|
-
}
|
|
35
|
-
this.map.set(key, { ...existing, state: 'completed', response });
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
async remove(key: string): Promise<void> {
|
|
39
|
-
this.map.delete(key);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
async get(key: string): Promise<IdempotencyRecord | undefined> {
|
|
43
|
-
const record = this.map.get(key);
|
|
44
|
-
if (record === undefined) {
|
|
45
|
-
return undefined;
|
|
46
|
-
}
|
|
47
|
-
if (this.isExpired(record)) {
|
|
48
|
-
this.map.delete(key);
|
|
49
|
-
return undefined;
|
|
50
|
-
}
|
|
51
|
-
return { ...record };
|
|
52
|
-
}
|
|
53
|
-
}
|
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import { IdempotencyModuleOptions } from '../interface/idempotency-module-options.interface';
|
|
2
|
-
import { IIdempotencyStore } from '../interface/idempotency-store.interface';
|
|
3
|
-
import { InMemoryIdempotencyStore } from './in-memory-idempotency-store';
|
|
4
|
-
import { defaultPrincipalExtractor, PrincipalExtractor } from './default-principal-extractor';
|
|
5
|
-
import {
|
|
6
|
-
DEFAULT_HEADER_NAME,
|
|
7
|
-
DEFAULT_TTL_MS,
|
|
8
|
-
DEFAULT_REQUIRE_KEY,
|
|
9
|
-
DEFAULT_REPLAY_HEADERS,
|
|
10
|
-
} from '../constant/idempotency.constants';
|
|
11
|
-
|
|
12
|
-
export interface ResolvedIdempotencyOptions {
|
|
13
|
-
store: IIdempotencyStore;
|
|
14
|
-
headerName: string;
|
|
15
|
-
ttlMs: number;
|
|
16
|
-
requireKey: boolean;
|
|
17
|
-
replayHeaders: string[];
|
|
18
|
-
principalExtractor: PrincipalExtractor;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export type InterceptorOptions = Omit<ResolvedIdempotencyOptions, 'store'>;
|
|
22
|
-
|
|
23
|
-
export function resolveIdempotencyOptions(options: IdempotencyModuleOptions | undefined): ResolvedIdempotencyOptions {
|
|
24
|
-
return {
|
|
25
|
-
store: options?.store ?? new InMemoryIdempotencyStore({ ttlMs: options?.ttlMs ?? DEFAULT_TTL_MS }),
|
|
26
|
-
headerName: options?.headerName ?? DEFAULT_HEADER_NAME,
|
|
27
|
-
ttlMs: options?.ttlMs ?? DEFAULT_TTL_MS,
|
|
28
|
-
requireKey: options?.requireKey ?? DEFAULT_REQUIRE_KEY,
|
|
29
|
-
replayHeaders: options?.replayHeaders ?? DEFAULT_REPLAY_HEADERS,
|
|
30
|
-
principalExtractor: options?.principalExtractor ?? defaultPrincipalExtractor,
|
|
31
|
-
};
|
|
32
|
-
}
|
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from '@jest/globals';
|
|
2
|
-
import {
|
|
3
|
-
IdempotencyModule,
|
|
4
|
-
IdempotencyInterceptor,
|
|
5
|
-
Idempotent,
|
|
6
|
-
InMemoryIdempotencyStore,
|
|
7
|
-
IdempotencyConflictException,
|
|
8
|
-
IdempotencyKeyReuseException,
|
|
9
|
-
} from '../../lib';
|
|
10
|
-
|
|
11
|
-
describe('Package barrel — lib/index public surface', () => {
|
|
12
|
-
describe('AC5: every public symbol exported from the package barrel has the expected kind', () => {
|
|
13
|
-
it('AC5: IdempotencyModule is a constructor (function)', () => {
|
|
14
|
-
expect(IdempotencyModule).toBeInstanceOf(Function);
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
it('AC5: IdempotencyInterceptor is a constructor (function)', () => {
|
|
18
|
-
expect(IdempotencyInterceptor).toBeInstanceOf(Function);
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
it('AC5: Idempotent is a function (the @Idempotent() decorator factory)', () => {
|
|
22
|
-
expect(typeof Idempotent).toBe('function');
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
it('AC5: new InMemoryIdempotencyStore() is an InMemoryIdempotencyStore', () => {
|
|
26
|
-
const store = new InMemoryIdempotencyStore();
|
|
27
|
-
expect(store).toBeInstanceOf(InMemoryIdempotencyStore);
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
it('AC5: new IdempotencyConflictException() is an IdempotencyConflictException', () => {
|
|
31
|
-
const err = new IdempotencyConflictException();
|
|
32
|
-
expect(err).toBeInstanceOf(IdempotencyConflictException);
|
|
33
|
-
});
|
|
34
|
-
|
|
35
|
-
it('AC5: new IdempotencyKeyReuseException() is an IdempotencyKeyReuseException', () => {
|
|
36
|
-
const err = new IdempotencyKeyReuseException();
|
|
37
|
-
expect(err).toBeInstanceOf(IdempotencyKeyReuseException);
|
|
38
|
-
});
|
|
39
|
-
});
|
|
40
|
-
});
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from '@jest/globals';
|
|
2
|
-
import { IDEMPOTENCY_STORE, IDEMPOTENCY_MODULE_OPTIONS } from '../../lib/constant/idempotency.constants';
|
|
3
|
-
|
|
4
|
-
describe('idempotency constants', () => {
|
|
5
|
-
it('AC11: IDEMPOTENCY_STORE and IDEMPOTENCY_MODULE_OPTIONS are defined; IDEMPOTENCY_STORE equals Symbol.for("IDEMPOTENCY_STORE")', () => {
|
|
6
|
-
expect(IDEMPOTENCY_STORE).toBeDefined();
|
|
7
|
-
expect(IDEMPOTENCY_MODULE_OPTIONS).toBeDefined();
|
|
8
|
-
expect(IDEMPOTENCY_STORE).toBe(Symbol.for('IDEMPOTENCY_STORE'));
|
|
9
|
-
});
|
|
10
|
-
});
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import 'reflect-metadata';
|
|
2
|
-
import { describe, expect, it } from '@jest/globals';
|
|
3
|
-
import { Reflector } from '@nestjs/core';
|
|
4
|
-
import { Idempotent } from '../../lib/decorator/idempotent.decorator';
|
|
5
|
-
import { IDEMPOTENT_METADATA_KEY } from '../../lib/constant/idempotency.constants';
|
|
6
|
-
|
|
7
|
-
describe('@Idempotent()', () => {
|
|
8
|
-
it('AC8: decorated method carries reflected metadata true; undecorated method returns undefined', () => {
|
|
9
|
-
class TestClass {
|
|
10
|
-
@Idempotent()
|
|
11
|
-
decorated() { return; }
|
|
12
|
-
|
|
13
|
-
undecorated() { return; }
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
const reflector = new Reflector();
|
|
17
|
-
expect(reflector.get(IDEMPOTENT_METADATA_KEY, TestClass.prototype.decorated)).toBe(true);
|
|
18
|
-
expect(reflector.get(IDEMPOTENT_METADATA_KEY, TestClass.prototype.undecorated)).toBeUndefined();
|
|
19
|
-
});
|
|
20
|
-
});
|