@aligent/aws-wrappers 0.4.1 → 0.5.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/README.md +65 -2
- package/cjs/index.cjs +46 -12
- package/cjs/package.json +11 -1
- package/cjs/src/dynamodb/dynamodb.d.ts +4 -1
- package/cjs/src/ssm/ssm.d.ts +5 -0
- package/cjs/src/testing/testing.d.ts +44 -0
- package/cjs/testing.cjs +95 -0
- package/cjs/testing.d.ts +1 -0
- package/docs/{classes → index/classes}/DynamoDBService.md +18 -15
- package/docs/{classes → index/classes}/S3Service.md +17 -17
- package/docs/{classes → index/classes}/SNSService.md +6 -6
- package/docs/{classes → index/classes}/SQSService.md +9 -9
- package/docs/{classes → index/classes}/SSMService.md +14 -9
- package/docs/{classes → index/classes}/SchedulerService.md +13 -13
- package/docs/{classes → index/classes}/SecretsManagerService.md +10 -10
- package/docs/{classes → index/classes}/StepFunctionsService.md +8 -8
- package/docs/index/modules.md +18 -0
- package/docs/modules.md +3 -9
- package/docs/testing/testing/functions/createMockService.md +79 -0
- package/docs/testing/testing/modules.md +11 -0
- package/esm/index.mjs +46 -12
- package/esm/package.json +11 -1
- package/esm/src/dynamodb/dynamodb.d.ts +4 -1
- package/esm/src/ssm/ssm.d.ts +5 -0
- package/esm/src/testing/testing.d.ts +44 -0
- package/esm/testing.d.ts +1 -0
- package/esm/testing.mjs +93 -0
- package/package.json +11 -1
package/README.md
CHANGED
|
@@ -159,7 +159,7 @@ for await (const item of ddb.paginateItems<{ pk: string }>({
|
|
|
159
159
|
|
|
160
160
|
`Limit` on `paginateItems` / `paginateScan` is applied by DynamoDB per request, and both methods walk every page until `LastEvaluatedKey` is exhausted. Passing `Limit: 10` therefore yields *every* matching item in pages of 10, not the first 10. Because both return an `AsyncGenerator`, `break` calls its `return()`, which unwinds the pagination and issues no further requests — that is how you bound the number of items. `Limit` is still the right knob for tuning per-request consumed capacity and page memory; it just doesn't stop the walk.
|
|
161
161
|
|
|
162
|
-
`batchGet` is **not** generic — its `Responses` field is a multi-table record whose item shapes can differ per table, so no single generic can soundly describe it. Callers should narrow the result type at the call site.
|
|
162
|
+
`batchGet` is **not** generic — its `Responses` field is a multi-table record whose item shapes can differ per table, so no single generic can soundly describe it. Callers should narrow the result type at the call site. Like `batchWrite`, it retries non-empty `UnprocessedKeys` with jittered exponential backoff (5 attempts, 200ms base), merging `Responses` across attempts and throwing if keys remain unprocessed after the final attempt.
|
|
163
163
|
|
|
164
164
|
## Secrets Manager
|
|
165
165
|
|
|
@@ -272,7 +272,8 @@ const ssm = new SSMService();
|
|
|
272
272
|
const apiKey = await ssm.getParameter('/myapp/api-key');
|
|
273
273
|
|
|
274
274
|
// Supply an alias-to-path map — the result is keyed by the aliases so the
|
|
275
|
-
// SSM path is only mentioned at the call site.
|
|
275
|
+
// SSM path is only mentioned at the call site. Auto-chunks past 10 aliases
|
|
276
|
+
// (the SDK's per-request cap on GetParameters).
|
|
276
277
|
const { host, port } = await ssm.getParameters({
|
|
277
278
|
host: '/myapp/host',
|
|
278
279
|
port: '/myapp/port',
|
|
@@ -352,6 +353,68 @@ await truncSns.publish({ TopicArn, Message: huge, Subject: long });
|
|
|
352
353
|
await truncSns.publish({ TopicArn, Message: huge }, { truncate: false });
|
|
353
354
|
```
|
|
354
355
|
|
|
356
|
+
## Testing
|
|
357
|
+
|
|
358
|
+
When you unit-test code that takes a wrapper as a dependency, you usually want to assert that *your* code called the right method with the right arguments — not to exercise the wrapper's chunking, pagination or JSON round-tripping, which this package already covers with its own tests against a mocked SDK client.
|
|
359
|
+
|
|
360
|
+
`createMockService` builds a stand-in for a service class from an object of method overrides. It ships from the `@aligent/aws-wrappers/testing` subpath — it is deliberately not exported from the package root, so test scaffolding can never be reached from the module your Lambda bundles.
|
|
361
|
+
|
|
362
|
+
```ts
|
|
363
|
+
// report-handler.ts
|
|
364
|
+
import type { S3Service } from '@aligent/aws-wrappers';
|
|
365
|
+
|
|
366
|
+
export async function reportHandler({ s3 }: { s3: S3Service }) {
|
|
367
|
+
const report = await s3.getJsonObject<{ total: number }>({
|
|
368
|
+
Bucket: 'reports',
|
|
369
|
+
Key: 'daily.json',
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
return { statusCode: 200, body: `Total: ${report?.total ?? 0}` };
|
|
373
|
+
}
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
```ts
|
|
377
|
+
// report-handler.test.ts
|
|
378
|
+
import { S3Service } from '@aligent/aws-wrappers';
|
|
379
|
+
import { createMockService } from '@aligent/aws-wrappers/testing';
|
|
380
|
+
import { expect, it, vi } from 'vitest';
|
|
381
|
+
import { reportHandler } from './report-handler.js';
|
|
382
|
+
|
|
383
|
+
it('reads the daily report from S3', async () => {
|
|
384
|
+
const getJsonObject = vi.fn().mockResolvedValue({ total: 42 });
|
|
385
|
+
const s3 = createMockService(S3Service, { getJsonObject });
|
|
386
|
+
|
|
387
|
+
const result = await reportHandler({ s3 });
|
|
388
|
+
|
|
389
|
+
expect(getJsonObject).toHaveBeenCalledWith({ Bucket: 'reports', Key: 'daily.json' });
|
|
390
|
+
expect(result.body).toBe('Total: 42');
|
|
391
|
+
});
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
- **No cast at the call site.** The returned value is accepted wherever the real class is expected.
|
|
395
|
+
- **Override keys are type-checked** against the class's public surface, so a misspelled key is a compile error rather than a green test that exercised nothing. For a non-generic method you can type the spy — `vi.fn<SQSService['sendMessage']>()` — to have its shape checked against the real method too.
|
|
396
|
+
- **Only mock what the code under test calls.** Accessing any other method of the class throws `S3Service.headObject was accessed but not mocked`, naming both the service and the method, instead of failing later as `is not a function`.
|
|
397
|
+
- **Bring your own spies.** The helper imports no test framework — `vi.fn()`, `jest.fn()` or a hand-rolled closure all work, and overridden keys keep your spy's type, so `s3.getJsonObject.mock.calls` typechecks through the returned object.
|
|
398
|
+
|
|
399
|
+
### Overriding a generic method
|
|
400
|
+
|
|
401
|
+
Several methods are generic in their return type — `S3Service.getJsonObject` / `putJsonObject` / `getAllObjects`, `DynamoDBService.putItem` / `query` / `scan`, `SecretsManagerService.getJsonSecret` and `SSMService.getParameters`. An override has to satisfy the generic signature, so a plain non-generic function is rejected:
|
|
402
|
+
|
|
403
|
+
```ts
|
|
404
|
+
// Error: '{ total: number }' is not assignable to 'T'
|
|
405
|
+
const getJsonObject = async () => ({ total: 42 });
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
An untyped `vi.fn()` is the easy path and is what the example above uses — `Mock`'s call signature is loose enough to satisfy the constraint. Otherwise make the override generic:
|
|
409
|
+
|
|
410
|
+
```ts
|
|
411
|
+
const getJsonObject = async <T>() => ({ total: 42 }) as T;
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
Note that the typed-spy form does **not** work here: `vi.fn<S3Service['getJsonObject']>()` produces a `Mock` that erases the type parameter and is no longer assignable to the generic signature. Reach for a typed spy on non-generic methods only.
|
|
415
|
+
|
|
416
|
+
The helper is generic over any class, so it works for all eight wrappers and for your own service classes too.
|
|
417
|
+
|
|
355
418
|
## Build / test
|
|
356
419
|
|
|
357
420
|
```sh
|
package/cjs/index.cjs
CHANGED
|
@@ -54,6 +54,8 @@ function filterFieldsForLogLevel(logger, input, safeFields) {
|
|
|
54
54
|
|
|
55
55
|
const BATCH_WRITE_MAX_ATTEMPTS = 5;
|
|
56
56
|
const BATCH_WRITE_BASE_DELAY_MS = 200;
|
|
57
|
+
const BATCH_GET_MAX_ATTEMPTS = 5;
|
|
58
|
+
const BATCH_GET_BASE_DELAY_MS = 200;
|
|
57
59
|
/**
|
|
58
60
|
* Fields safe to log at INFO. Omits `Key` (may carry customer IDs / tenant IDs).
|
|
59
61
|
*/
|
|
@@ -139,8 +141,8 @@ const SCAN_SAFE_FIELDS = [
|
|
|
139
141
|
'ReturnConsumedCapacity',
|
|
140
142
|
];
|
|
141
143
|
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
142
|
-
const backoffDelay = (attempt) => {
|
|
143
|
-
const exp =
|
|
144
|
+
const backoffDelay = (attempt, baseDelayMs) => {
|
|
145
|
+
const exp = baseDelayMs * 2 ** attempt;
|
|
144
146
|
return exp + Math.random() * exp;
|
|
145
147
|
};
|
|
146
148
|
/**
|
|
@@ -268,7 +270,10 @@ class DynamoDBService {
|
|
|
268
270
|
return response;
|
|
269
271
|
}
|
|
270
272
|
/**
|
|
271
|
-
* Batch-get items from one or more DynamoDB tables
|
|
273
|
+
* Batch-get items from one or more DynamoDB tables, retrying
|
|
274
|
+
* `UnprocessedKeys` with jittered exponential backoff. Up to 5 attempts
|
|
275
|
+
* (200ms base delay). Throws when keys remain unprocessed after the final
|
|
276
|
+
* attempt. `Responses` are merged across attempts, keyed by table name.
|
|
272
277
|
*
|
|
273
278
|
* Note: this method is intentionally **not** generic. `BatchGet`'s
|
|
274
279
|
* `Responses` field is a multi-table `Record<string, item[]>` whose item
|
|
@@ -284,7 +289,26 @@ class DynamoDBService {
|
|
|
284
289
|
this.logger.info('Batch getting DynamoDB items', {
|
|
285
290
|
input: logFullInput ? input : { tables: Object.keys(input.RequestItems ?? {}) },
|
|
286
291
|
});
|
|
287
|
-
|
|
292
|
+
let current = input;
|
|
293
|
+
const mergedResponses = {};
|
|
294
|
+
for (let attempt = 0; attempt < BATCH_GET_MAX_ATTEMPTS; attempt++) {
|
|
295
|
+
const response = await this.client.send(new libDynamodb.BatchGetCommand(current));
|
|
296
|
+
for (const [table, items] of Object.entries(response.Responses ?? {})) {
|
|
297
|
+
mergedResponses[table] = [...(mergedResponses[table] ?? []), ...items];
|
|
298
|
+
}
|
|
299
|
+
const unprocessed = response.UnprocessedKeys;
|
|
300
|
+
if (!unprocessed || Object.keys(unprocessed).length === 0) {
|
|
301
|
+
return { ...response, Responses: mergedResponses };
|
|
302
|
+
}
|
|
303
|
+
this.logger.warn('Retrying unprocessed DynamoDB items', {
|
|
304
|
+
attempt: attempt + 1,
|
|
305
|
+
tables: Object.keys(unprocessed),
|
|
306
|
+
});
|
|
307
|
+
if (attempt < BATCH_GET_MAX_ATTEMPTS - 1)
|
|
308
|
+
await sleep(backoffDelay(attempt, BATCH_GET_BASE_DELAY_MS));
|
|
309
|
+
current = { ...input, RequestItems: unprocessed };
|
|
310
|
+
}
|
|
311
|
+
throw new Error(`batchGet failed after ${BATCH_GET_MAX_ATTEMPTS} attempts`);
|
|
288
312
|
}
|
|
289
313
|
/**
|
|
290
314
|
* Batch-write items to DynamoDB, retrying `UnprocessedItems` with jittered
|
|
@@ -311,7 +335,7 @@ class DynamoDBService {
|
|
|
311
335
|
tables: Object.keys(unprocessed),
|
|
312
336
|
});
|
|
313
337
|
if (attempt < BATCH_WRITE_MAX_ATTEMPTS - 1)
|
|
314
|
-
await sleep(backoffDelay(attempt));
|
|
338
|
+
await sleep(backoffDelay(attempt, BATCH_WRITE_BASE_DELAY_MS));
|
|
315
339
|
current = { ...input, RequestItems: unprocessed };
|
|
316
340
|
}
|
|
317
341
|
throw new Error(`batchWrite failed after ${BATCH_WRITE_MAX_ATTEMPTS} attempts`);
|
|
@@ -1278,6 +1302,7 @@ class SQSService {
|
|
|
1278
1302
|
}
|
|
1279
1303
|
}
|
|
1280
1304
|
|
|
1305
|
+
const GET_PARAMETERS_LIMIT = 10;
|
|
1281
1306
|
/**
|
|
1282
1307
|
* Fields safe to log at INFO level for `putParameter`. Omits `Value` (the
|
|
1283
1308
|
* parameter content itself).
|
|
@@ -1347,6 +1372,11 @@ class SSMService {
|
|
|
1347
1372
|
* });
|
|
1348
1373
|
* ```
|
|
1349
1374
|
*
|
|
1375
|
+
* The AWS SSM `GetParameters` API caps requests at
|
|
1376
|
+
* `GET_PARAMETERS_LIMIT` (10) names per call, so this method auto-chunks
|
|
1377
|
+
* the underlying parameter names and sends one request per chunk,
|
|
1378
|
+
* merging the results before building the alias-keyed return value.
|
|
1379
|
+
*
|
|
1350
1380
|
* @param aliases - Record mapping each desired local alias to its SSM
|
|
1351
1381
|
* parameter name (or ARN).
|
|
1352
1382
|
* @returns A record keyed by the same aliases, mapping each to the
|
|
@@ -1355,14 +1385,18 @@ class SSMService {
|
|
|
1355
1385
|
*/
|
|
1356
1386
|
async getParameters(aliases) {
|
|
1357
1387
|
this.logger.info('Fetching SSM parameters', { input: { aliases } });
|
|
1358
|
-
const
|
|
1359
|
-
Names: Object.values(aliases),
|
|
1360
|
-
WithDecryption: true,
|
|
1361
|
-
}));
|
|
1388
|
+
const names = Object.values(aliases);
|
|
1362
1389
|
const byPath = new Map();
|
|
1363
|
-
for (
|
|
1364
|
-
|
|
1365
|
-
|
|
1390
|
+
for (let i = 0; i < names.length; i += GET_PARAMETERS_LIMIT) {
|
|
1391
|
+
const chunk = names.slice(i, i + GET_PARAMETERS_LIMIT);
|
|
1392
|
+
const response = await this.client.send(new clientSsm.GetParametersCommand({
|
|
1393
|
+
Names: chunk,
|
|
1394
|
+
WithDecryption: true,
|
|
1395
|
+
}));
|
|
1396
|
+
for (const parameter of response.Parameters ?? []) {
|
|
1397
|
+
if (parameter.Name !== undefined)
|
|
1398
|
+
byPath.set(parameter.Name, parameter.Value);
|
|
1399
|
+
}
|
|
1366
1400
|
}
|
|
1367
1401
|
const result = {};
|
|
1368
1402
|
for (const alias of Object.keys(aliases)) {
|
package/cjs/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aligent/aws-wrappers",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "Opinionated AWS SDK wrappers with Powertools logging and X-Ray tracing",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=18"
|
|
@@ -19,6 +19,16 @@
|
|
|
19
19
|
"default": "./cjs/index.cjs"
|
|
20
20
|
}
|
|
21
21
|
},
|
|
22
|
+
"./testing": {
|
|
23
|
+
"import": {
|
|
24
|
+
"types": "./esm/src/testing/testing.d.ts",
|
|
25
|
+
"default": "./esm/testing.mjs"
|
|
26
|
+
},
|
|
27
|
+
"require": {
|
|
28
|
+
"types": "./cjs/src/testing/testing.d.ts",
|
|
29
|
+
"default": "./cjs/testing.cjs"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
22
32
|
"./package.json": "./package.json"
|
|
23
33
|
},
|
|
24
34
|
"files": [
|
|
@@ -103,7 +103,10 @@ export declare class DynamoDBService {
|
|
|
103
103
|
Items?: T[];
|
|
104
104
|
}>;
|
|
105
105
|
/**
|
|
106
|
-
* Batch-get items from one or more DynamoDB tables
|
|
106
|
+
* Batch-get items from one or more DynamoDB tables, retrying
|
|
107
|
+
* `UnprocessedKeys` with jittered exponential backoff. Up to 5 attempts
|
|
108
|
+
* (200ms base delay). Throws when keys remain unprocessed after the final
|
|
109
|
+
* attempt. `Responses` are merged across attempts, keyed by table name.
|
|
107
110
|
*
|
|
108
111
|
* Note: this method is intentionally **not** generic. `BatchGet`'s
|
|
109
112
|
* `Responses` field is a multi-table `Record<string, item[]>` whose item
|
package/cjs/src/ssm/ssm.d.ts
CHANGED
|
@@ -49,6 +49,11 @@ export declare class SSMService {
|
|
|
49
49
|
* });
|
|
50
50
|
* ```
|
|
51
51
|
*
|
|
52
|
+
* The AWS SSM `GetParameters` API caps requests at
|
|
53
|
+
* `GET_PARAMETERS_LIMIT` (10) names per call, so this method auto-chunks
|
|
54
|
+
* the underlying parameter names and sends one request per chunk,
|
|
55
|
+
* merging the results before building the alias-keyed return value.
|
|
56
|
+
*
|
|
52
57
|
* @param aliases - Record mapping each desired local alias to its SSM
|
|
53
58
|
* parameter name (or ARN).
|
|
54
59
|
* @returns A record keyed by the same aliases, mapping each to the
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build a stand-in for a service class from an object of method overrides, for
|
|
3
|
+
* use in unit tests of code that depends on the service.
|
|
4
|
+
*
|
|
5
|
+
* Accessing a method of the class that was not overridden throws immediately,
|
|
6
|
+
* naming the service and the method, rather than failing later as
|
|
7
|
+
* `is not a function`. Any key that is neither an override nor a method of the
|
|
8
|
+
* class falls through to the overrides object — so `toString`, `valueOf` and
|
|
9
|
+
* `constructor` resolve from `Object.prototype` as usual, and anything else is
|
|
10
|
+
* `undefined`. That fallback is what keeps probe properties safe: `then` (so
|
|
11
|
+
* awaiting the mock does not throw), `Symbol.toStringTag`, inspection symbols,
|
|
12
|
+
* and whatever a test framework's error serialiser reaches for.
|
|
13
|
+
*
|
|
14
|
+
* Only the overrides are enumerable, so spreading, serialising or deep-equalling
|
|
15
|
+
* an object that holds the mock does not trip the throw.
|
|
16
|
+
*
|
|
17
|
+
* The helper imports no test framework: callers supply their own spies, and
|
|
18
|
+
* overridden keys keep the caller's spy type so `.mock` resolves through the
|
|
19
|
+
* returned object.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```typescript
|
|
23
|
+
* const getJsonObject = vi.fn().mockResolvedValue({ id: 1 });
|
|
24
|
+
* const s3 = createMockService(S3Service, { getJsonObject });
|
|
25
|
+
*
|
|
26
|
+
* await handler({ s3 });
|
|
27
|
+
*
|
|
28
|
+
* expect(s3.getJsonObject.mock.calls).toHaveLength(1);
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @param service - The service class itself. It is never constructed — only
|
|
32
|
+
* its prototype is read — so the parameter is typed as just that capability,
|
|
33
|
+
* which also accepts abstract classes and classes with required constructor
|
|
34
|
+
* arguments. Passing the class as a value (rather than as an explicit type
|
|
35
|
+
* argument) is load-bearing for the types: TypeScript has no partial
|
|
36
|
+
* type-argument inference, so an explicit `T` would suppress inference of the
|
|
37
|
+
* overrides type and lose the caller's spy typing on overridden keys.
|
|
38
|
+
* @param overrides - The methods the code under test actually calls. Keys are
|
|
39
|
+
* checked against the class's public surface, so a typo or a wrong-shaped
|
|
40
|
+
* override is a compile error.
|
|
41
|
+
*/
|
|
42
|
+
export declare function createMockService<T extends object, O extends Partial<T>>(service: {
|
|
43
|
+
prototype: T;
|
|
44
|
+
}, overrides: O): T & O;
|
package/cjs/testing.cjs
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Collect the method names of a class, walking the prototype chain up to but
|
|
5
|
+
* excluding `Object.prototype` so inherited methods are found.
|
|
6
|
+
*
|
|
7
|
+
* Property *descriptors* are inspected rather than properties read: reading a
|
|
8
|
+
* prototype getter here would execute consumer code with `this` bound to the
|
|
9
|
+
* mock. Accessor properties are therefore neither mockable nor throwable.
|
|
10
|
+
*/
|
|
11
|
+
function collectMethodNames(prototype) {
|
|
12
|
+
const names = new Set();
|
|
13
|
+
let current = prototype;
|
|
14
|
+
while (current !== null && current !== Object.prototype) {
|
|
15
|
+
for (const key of Object.getOwnPropertyNames(current)) {
|
|
16
|
+
if (key === 'constructor')
|
|
17
|
+
continue;
|
|
18
|
+
const descriptor = Object.getOwnPropertyDescriptor(current, key);
|
|
19
|
+
if (typeof descriptor?.value === 'function')
|
|
20
|
+
names.add(key);
|
|
21
|
+
}
|
|
22
|
+
current = Object.getPrototypeOf(current);
|
|
23
|
+
}
|
|
24
|
+
return names;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Build a stand-in for a service class from an object of method overrides, for
|
|
28
|
+
* use in unit tests of code that depends on the service.
|
|
29
|
+
*
|
|
30
|
+
* Accessing a method of the class that was not overridden throws immediately,
|
|
31
|
+
* naming the service and the method, rather than failing later as
|
|
32
|
+
* `is not a function`. Any key that is neither an override nor a method of the
|
|
33
|
+
* class falls through to the overrides object — so `toString`, `valueOf` and
|
|
34
|
+
* `constructor` resolve from `Object.prototype` as usual, and anything else is
|
|
35
|
+
* `undefined`. That fallback is what keeps probe properties safe: `then` (so
|
|
36
|
+
* awaiting the mock does not throw), `Symbol.toStringTag`, inspection symbols,
|
|
37
|
+
* and whatever a test framework's error serialiser reaches for.
|
|
38
|
+
*
|
|
39
|
+
* Only the overrides are enumerable, so spreading, serialising or deep-equalling
|
|
40
|
+
* an object that holds the mock does not trip the throw.
|
|
41
|
+
*
|
|
42
|
+
* The helper imports no test framework: callers supply their own spies, and
|
|
43
|
+
* overridden keys keep the caller's spy type so `.mock` resolves through the
|
|
44
|
+
* returned object.
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* ```typescript
|
|
48
|
+
* const getJsonObject = vi.fn().mockResolvedValue({ id: 1 });
|
|
49
|
+
* const s3 = createMockService(S3Service, { getJsonObject });
|
|
50
|
+
*
|
|
51
|
+
* await handler({ s3 });
|
|
52
|
+
*
|
|
53
|
+
* expect(s3.getJsonObject.mock.calls).toHaveLength(1);
|
|
54
|
+
* ```
|
|
55
|
+
*
|
|
56
|
+
* @param service - The service class itself. It is never constructed — only
|
|
57
|
+
* its prototype is read — so the parameter is typed as just that capability,
|
|
58
|
+
* which also accepts abstract classes and classes with required constructor
|
|
59
|
+
* arguments. Passing the class as a value (rather than as an explicit type
|
|
60
|
+
* argument) is load-bearing for the types: TypeScript has no partial
|
|
61
|
+
* type-argument inference, so an explicit `T` would suppress inference of the
|
|
62
|
+
* overrides type and lose the caller's spy typing on overridden keys.
|
|
63
|
+
* @param overrides - The methods the code under test actually calls. Keys are
|
|
64
|
+
* checked against the class's public surface, so a typo or a wrong-shaped
|
|
65
|
+
* override is a compile error.
|
|
66
|
+
*/
|
|
67
|
+
function createMockService(service, overrides) {
|
|
68
|
+
const { prototype } = service;
|
|
69
|
+
const methodNames = collectMethodNames(prototype);
|
|
70
|
+
const className = prototype.constructor?.name;
|
|
71
|
+
const isUnmockedMethod = (key) => typeof key === 'string' && methodNames.has(key);
|
|
72
|
+
const mock = new Proxy(overrides, {
|
|
73
|
+
get(target, key, receiver) {
|
|
74
|
+
// `hasOwn`, not `has`: a class method that shadows one of
|
|
75
|
+
// `Object.prototype`'s (`toString`, `valueOf`, …) must still throw
|
|
76
|
+
// rather than be served silently from the prototype chain.
|
|
77
|
+
if (Object.hasOwn(target, key))
|
|
78
|
+
return Reflect.get(target, key, receiver);
|
|
79
|
+
if (isUnmockedMethod(key)) {
|
|
80
|
+
throw new Error(`${className ?? 'Service'}.${key} was accessed but not mocked`);
|
|
81
|
+
}
|
|
82
|
+
return Reflect.get(target, key, receiver);
|
|
83
|
+
},
|
|
84
|
+
has(target, key) {
|
|
85
|
+
return Reflect.has(target, key) || isUnmockedMethod(key);
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
// The services declare `private readonly client` / `private readonly logger`.
|
|
89
|
+
// Those fields are nominal, so no structurally-constructed value is
|
|
90
|
+
// assignable to the class type — this cast is unavoidable. Concentrating
|
|
91
|
+
// it here is the point of the helper: consumer test suites contain none.
|
|
92
|
+
return mock;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
exports.createMockService = createMockService;
|
package/cjs/testing.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./src/testing/testing";
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
[**@aligent/aws-wrappers**](
|
|
1
|
+
[**@aligent/aws-wrappers**](../../modules.md)
|
|
2
2
|
|
|
3
3
|
***
|
|
4
4
|
|
|
5
|
-
[@aligent/aws-wrappers](../modules.md) / DynamoDBService
|
|
5
|
+
[@aligent/aws-wrappers](../../modules.md) / [index](../modules.md) / DynamoDBService
|
|
6
6
|
|
|
7
7
|
# Class: DynamoDBService
|
|
8
8
|
|
|
9
|
-
Defined in: [dynamodb/dynamodb.ts:
|
|
9
|
+
Defined in: [dynamodb/dynamodb.ts:155](https://github.com/aligent/microservice-development-utilities/blob/71eddc43546914f2f8321d80003a486b30acef40/packages/aws-wrappers/src/dynamodb/dynamodb.ts#L155)
|
|
10
10
|
|
|
11
11
|
Wrapper around the AWS DynamoDB Document client providing structured
|
|
12
12
|
Powertools logging and X-Ray tracing by default.
|
|
@@ -26,7 +26,7 @@ callers work with plain TypeScript objects in both directions.
|
|
|
26
26
|
|
|
27
27
|
> **new DynamoDBService**(`opts?`): `DynamoDBService`
|
|
28
28
|
|
|
29
|
-
Defined in: [dynamodb/dynamodb.ts:
|
|
29
|
+
Defined in: [dynamodb/dynamodb.ts:168](https://github.com/aligent/microservice-development-utilities/blob/71eddc43546914f2f8321d80003a486b30acef40/packages/aws-wrappers/src/dynamodb/dynamodb.ts#L168)
|
|
30
30
|
|
|
31
31
|
#### Parameters
|
|
32
32
|
|
|
@@ -61,9 +61,12 @@ which picks up `POWERTOOLS_SERVICE_NAME` from the environment.
|
|
|
61
61
|
|
|
62
62
|
> **batchGet**(`input`): `Promise`\<`BatchGetCommandOutput`\>
|
|
63
63
|
|
|
64
|
-
Defined in: [dynamodb/dynamodb.ts:
|
|
64
|
+
Defined in: [dynamodb/dynamodb.ts:322](https://github.com/aligent/microservice-development-utilities/blob/71eddc43546914f2f8321d80003a486b30acef40/packages/aws-wrappers/src/dynamodb/dynamodb.ts#L322)
|
|
65
65
|
|
|
66
|
-
Batch-get items from one or more DynamoDB tables
|
|
66
|
+
Batch-get items from one or more DynamoDB tables, retrying
|
|
67
|
+
`UnprocessedKeys` with jittered exponential backoff. Up to 5 attempts
|
|
68
|
+
(200ms base delay). Throws when keys remain unprocessed after the final
|
|
69
|
+
attempt. `Responses` are merged across attempts, keyed by table name.
|
|
67
70
|
|
|
68
71
|
Note: this method is intentionally **not** generic. `BatchGet`'s
|
|
69
72
|
`Responses` field is a multi-table `Record<string, item[]>` whose item
|
|
@@ -88,7 +91,7 @@ Callers should narrow the result type at the call site.
|
|
|
88
91
|
|
|
89
92
|
> **batchWrite**(`input`): `Promise`\<`BatchWriteCommandOutput`\>
|
|
90
93
|
|
|
91
|
-
Defined in: [dynamodb/dynamodb.ts:
|
|
94
|
+
Defined in: [dynamodb/dynamodb.ts:359](https://github.com/aligent/microservice-development-utilities/blob/71eddc43546914f2f8321d80003a486b30acef40/packages/aws-wrappers/src/dynamodb/dynamodb.ts#L359)
|
|
92
95
|
|
|
93
96
|
Batch-write items to DynamoDB, retrying `UnprocessedItems` with jittered
|
|
94
97
|
exponential backoff. Up to 5 attempts (200ms base delay). Throws when
|
|
@@ -112,7 +115,7 @@ items remain unprocessed after the final attempt.
|
|
|
112
115
|
|
|
113
116
|
> **deleteItem**\<`K`, `R`\>(`input`): `Promise`\<`Omit`\<`DeleteCommandOutput`, `"Attributes"`\> & `object`\>
|
|
114
117
|
|
|
115
|
-
Defined in: [dynamodb/dynamodb.ts:
|
|
118
|
+
Defined in: [dynamodb/dynamodb.ts:249](https://github.com/aligent/microservice-development-utilities/blob/71eddc43546914f2f8321d80003a486b30acef40/packages/aws-wrappers/src/dynamodb/dynamodb.ts#L249)
|
|
116
119
|
|
|
117
120
|
Delete an item from DynamoDB. The `Attributes` field on the response is
|
|
118
121
|
typed as `R` — relevant when `ReturnValues: 'ALL_OLD'` is set.
|
|
@@ -149,7 +152,7 @@ Expected shape of the returned `Attributes`.
|
|
|
149
152
|
|
|
150
153
|
> **getItem**\<`K`, `R`\>(`input`): `Promise`\<`R` \| `undefined`\>
|
|
151
154
|
|
|
152
|
-
Defined in: [dynamodb/dynamodb.ts:
|
|
155
|
+
Defined in: [dynamodb/dynamodb.ts:183](https://github.com/aligent/microservice-development-utilities/blob/71eddc43546914f2f8321d80003a486b30acef40/packages/aws-wrappers/src/dynamodb/dynamodb.ts#L183)
|
|
153
156
|
|
|
154
157
|
Get an item from DynamoDB.
|
|
155
158
|
|
|
@@ -187,7 +190,7 @@ The item, or `undefined` if not found.
|
|
|
187
190
|
|
|
188
191
|
> **paginateItems**\<`T`\>(`input`): `AsyncGenerator`\<`T`\>
|
|
189
192
|
|
|
190
|
-
Defined in: [dynamodb/dynamodb.ts:
|
|
193
|
+
Defined in: [dynamodb/dynamodb.ts:410](https://github.com/aligent/microservice-development-utilities/blob/71eddc43546914f2f8321d80003a486b30acef40/packages/aws-wrappers/src/dynamodb/dynamodb.ts#L410)
|
|
191
194
|
|
|
192
195
|
Paginate over Query results, yielding one unmarshalled item at a time.
|
|
193
196
|
|
|
@@ -238,7 +241,7 @@ Expected shape of each yielded item.
|
|
|
238
241
|
|
|
239
242
|
> **paginateScan**\<`T`\>(`input`): `AsyncGenerator`\<`T`\>
|
|
240
243
|
|
|
241
|
-
Defined in: [dynamodb/dynamodb.ts:
|
|
244
|
+
Defined in: [dynamodb/dynamodb.ts:432](https://github.com/aligent/microservice-development-utilities/blob/71eddc43546914f2f8321d80003a486b30acef40/packages/aws-wrappers/src/dynamodb/dynamodb.ts#L432)
|
|
242
245
|
|
|
243
246
|
Paginate over Scan results, yielding one unmarshalled item at a time.
|
|
244
247
|
|
|
@@ -272,7 +275,7 @@ Expected shape of each yielded item.
|
|
|
272
275
|
|
|
273
276
|
> **putItem**\<`T`\>(`input`): `Promise`\<`PutCommandOutput`\>
|
|
274
277
|
|
|
275
|
-
Defined in: [dynamodb/dynamodb.ts:
|
|
278
|
+
Defined in: [dynamodb/dynamodb.ts:203](https://github.com/aligent/microservice-development-utilities/blob/71eddc43546914f2f8321d80003a486b30acef40/packages/aws-wrappers/src/dynamodb/dynamodb.ts#L203)
|
|
276
279
|
|
|
277
280
|
Put an item into DynamoDB. The caller's `Item` is typed as `T`, which
|
|
278
281
|
the document client marshalls automatically.
|
|
@@ -303,7 +306,7 @@ Type of the item being stored.
|
|
|
303
306
|
|
|
304
307
|
> **query**\<`T`\>(`input`): `Promise`\<`Omit`\<`QueryCommandOutput`, `"Items"`\> & `object`\>
|
|
305
308
|
|
|
306
|
-
Defined in: [dynamodb/dynamodb.ts:
|
|
309
|
+
Defined in: [dynamodb/dynamodb.ts:272](https://github.com/aligent/microservice-development-utilities/blob/71eddc43546914f2f8321d80003a486b30acef40/packages/aws-wrappers/src/dynamodb/dynamodb.ts#L272)
|
|
307
310
|
|
|
308
311
|
Execute a DynamoDB Query. The full `QueryCommandOutput` is returned with
|
|
309
312
|
`Items` typed as `T[]` so callers retain pagination metadata
|
|
@@ -335,7 +338,7 @@ Expected shape of each unmarshalled item.
|
|
|
335
338
|
|
|
336
339
|
> **scan**\<`T`\>(`input`): `Promise`\<`Omit`\<`ScanCommandOutput`, `"Items"`\> & `object`\>
|
|
337
340
|
|
|
338
|
-
Defined in: [dynamodb/dynamodb.ts:
|
|
341
|
+
Defined in: [dynamodb/dynamodb.ts:301](https://github.com/aligent/microservice-development-utilities/blob/71eddc43546914f2f8321d80003a486b30acef40/packages/aws-wrappers/src/dynamodb/dynamodb.ts#L301)
|
|
339
342
|
|
|
340
343
|
Scan a DynamoDB table. The full `ScanCommandOutput` is returned with
|
|
341
344
|
`Items` typed as `T[]` so callers retain pagination metadata.
|
|
@@ -379,7 +382,7 @@ Expected shape of each unmarshalled item.
|
|
|
379
382
|
|
|
380
383
|
> **updateItem**\<`K`, `R`\>(`input`): `Promise`\<`Omit`\<`UpdateCommandOutput`, `"Attributes"`\> & `object`\>
|
|
381
384
|
|
|
382
|
-
Defined in: [dynamodb/dynamodb.ts:
|
|
385
|
+
Defined in: [dynamodb/dynamodb.ts:226](https://github.com/aligent/microservice-development-utilities/blob/71eddc43546914f2f8321d80003a486b30acef40/packages/aws-wrappers/src/dynamodb/dynamodb.ts#L226)
|
|
383
386
|
|
|
384
387
|
Update an item in DynamoDB. The `Attributes` field on the response is
|
|
385
388
|
typed as `R` — the caller should choose `R` to match their
|