betterddb 0.8.1 → 0.8.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.
Files changed (82) hide show
  1. package/dist/src/betterddb.d.ts +137 -0
  2. package/dist/src/betterddb.d.ts.map +1 -0
  3. package/dist/src/betterddb.js +165 -0
  4. package/dist/src/betterddb.js.map +1 -0
  5. package/dist/src/builders/batch-get-builder.d.ts +16 -0
  6. package/dist/src/builders/batch-get-builder.d.ts.map +1 -0
  7. package/dist/src/builders/batch-get-builder.js +54 -0
  8. package/dist/src/builders/batch-get-builder.js.map +1 -0
  9. package/dist/src/builders/create-builder.d.ts +12 -0
  10. package/dist/src/builders/create-builder.d.ts.map +1 -0
  11. package/dist/src/builders/create-builder.js +84 -0
  12. package/dist/src/builders/create-builder.js.map +1 -0
  13. package/dist/src/builders/delete-builder.d.ts +18 -0
  14. package/dist/src/builders/delete-builder.d.ts.map +1 -0
  15. package/dist/src/builders/delete-builder.js +75 -0
  16. package/dist/src/builders/delete-builder.js.map +1 -0
  17. package/dist/src/builders/get-builder.d.ts +18 -0
  18. package/dist/src/builders/get-builder.d.ts.map +1 -0
  19. package/dist/src/builders/get-builder.js +76 -0
  20. package/dist/src/builders/get-builder.js.map +1 -0
  21. package/dist/src/builders/index.d.ts +8 -0
  22. package/dist/src/builders/index.d.ts.map +1 -0
  23. package/{src/builders/index.ts → dist/src/builders/index.js} +1 -0
  24. package/dist/src/builders/index.js.map +1 -0
  25. package/dist/src/builders/query-builder.d.ts +29 -0
  26. package/dist/src/builders/query-builder.d.ts.map +1 -0
  27. package/dist/src/builders/query-builder.js +171 -0
  28. package/dist/src/builders/query-builder.js.map +1 -0
  29. package/dist/src/builders/scan-builder.d.ts +21 -0
  30. package/dist/src/builders/scan-builder.d.ts.map +1 -0
  31. package/dist/src/builders/scan-builder.js +76 -0
  32. package/dist/src/builders/scan-builder.js.map +1 -0
  33. package/dist/src/builders/update-builder.d.ts +37 -0
  34. package/dist/src/builders/update-builder.d.ts.map +1 -0
  35. package/dist/src/builders/update-builder.js +301 -0
  36. package/dist/src/builders/update-builder.js.map +1 -0
  37. package/dist/src/index.d.ts +5 -0
  38. package/dist/src/index.d.ts.map +1 -0
  39. package/{src/index.ts → dist/src/index.js} +1 -0
  40. package/dist/src/index.js.map +1 -0
  41. package/dist/src/operator.d.ts +3 -0
  42. package/dist/src/operator.d.ts.map +1 -0
  43. package/dist/src/operator.js +28 -0
  44. package/dist/src/operator.js.map +1 -0
  45. package/dist/src/types/index.d.ts +2 -0
  46. package/dist/src/types/index.d.ts.map +1 -0
  47. package/{src/types/index.ts → dist/src/types/index.js} +1 -0
  48. package/dist/src/types/index.js.map +1 -0
  49. package/dist/src/types/paginated-result.d.ts +6 -0
  50. package/dist/src/types/paginated-result.d.ts.map +1 -0
  51. package/dist/src/types/paginated-result.js +2 -0
  52. package/dist/src/types/paginated-result.js.map +1 -0
  53. package/dist/tsconfig.tsbuildinfo +1 -0
  54. package/package.json +9 -8
  55. package/.github/workflows/npm-publish.yml +0 -33
  56. package/.github/workflows/test.yml +0 -42
  57. package/CONTRIBUTING.md +0 -225
  58. package/LICENCSE +0 -21
  59. package/babel.config.cjs +0 -6
  60. package/docker-compose.yml +0 -16
  61. package/eslint.config.mjs +0 -29
  62. package/jest.config.cjs +0 -17
  63. package/prettier.config.js +0 -6
  64. package/src/betterddb.ts +0 -268
  65. package/src/builders/batch-get-builder.ts +0 -57
  66. package/src/builders/create-builder.ts +0 -98
  67. package/src/builders/delete-builder.ts +0 -88
  68. package/src/builders/get-builder.ts +0 -79
  69. package/src/builders/query-builder.ts +0 -243
  70. package/src/builders/scan-builder.ts +0 -99
  71. package/src/builders/update-builder.ts +0 -371
  72. package/src/operator.ts +0 -43
  73. package/src/types/paginated-result.ts +0 -6
  74. package/test/batch-get.test.ts +0 -122
  75. package/test/create.test.ts +0 -121
  76. package/test/delete.test.ts +0 -93
  77. package/test/get.test.ts +0 -98
  78. package/test/query.test.ts +0 -206
  79. package/test/scan.test.ts +0 -130
  80. package/test/update.test.ts +0 -355
  81. package/test/utils/table-setup.ts +0 -62
  82. package/tsconfig.json +0 -23
@@ -1,371 +0,0 @@
1
- /* eslint-disable no-unused-vars */
2
- import {
3
- type NativeAttributeValue,
4
- TransactWriteCommand,
5
- UpdateCommand,
6
- type UpdateCommandInput,
7
- } from "@aws-sdk/lib-dynamodb";
8
- import { type BetterDDB } from "../betterddb.js";
9
- import {
10
- type TransactWriteItem,
11
- type Update,
12
- type ReturnValue,
13
- } from "@aws-sdk/client-dynamodb";
14
-
15
- interface UpdateActions<T> {
16
- set?: Partial<T>;
17
- remove?: (keyof T)[];
18
- add?: Partial<Record<keyof T, number | Set<NativeAttributeValue>>>;
19
- delete?: Partial<Record<keyof T, Set<NativeAttributeValue>>>;
20
- }
21
-
22
- export class UpdateBuilder<T> {
23
- private actions: UpdateActions<T> = {};
24
- private condition?: {
25
- expression: string;
26
- attributeValues: Record<string, NativeAttributeValue>;
27
- attributeNames: Record<string, string>;
28
- };
29
- // When using transaction mode, we store extra transaction items.
30
- private extraTransactItems: TransactWriteItem[] = [];
31
-
32
- // Reference to the parent BetterDDB instance and key.
33
- constructor(
34
- private parent: BetterDDB<T>,
35
- private key: Partial<T>,
36
- ) {}
37
-
38
- // Chainable methods:
39
- public set(attrs: Partial<T>): this {
40
- // Separate values into sets and removes
41
- const { toSet, toRemove } = Object.entries(attrs).reduce(
42
- (acc, [key, value]) => {
43
- if (
44
- value === undefined ||
45
- (typeof value === "string" &&
46
- value.trim() === "" &&
47
- this.parent.getSchema().shape[key]?.isOptional?.())
48
- ) {
49
- acc.toRemove.push(key as keyof T);
50
- } else {
51
- acc.toSet[key] = value;
52
- }
53
- return acc;
54
- },
55
- { toSet: {} as Record<string, any>, toRemove: [] as (keyof T)[] },
56
- );
57
-
58
- // Handle non-empty values with set
59
- if (Object.keys(toSet).length > 0) {
60
- const partialSchema = this.parent.getSchema().partial();
61
- const validated = partialSchema.parse(toSet);
62
- this.actions.set = { ...this.actions.set, ...validated };
63
- }
64
-
65
- // Handle empty/undefined values with remove
66
- if (toRemove.length > 0) {
67
- this.remove(toRemove);
68
- }
69
-
70
- return this;
71
- }
72
-
73
- public remove(attrs: (keyof T)[]): this {
74
- this.actions.remove = [...(this.actions.remove ?? []), ...attrs];
75
- return this;
76
- }
77
-
78
- public add(
79
- attrs: Partial<Record<keyof T, number | Set<NativeAttributeValue>>>,
80
- ): this {
81
- const partialSchema = this.parent.getSchema().partial();
82
- const validated = partialSchema.parse(attrs);
83
- this.actions.add = { ...this.actions.add, ...validated };
84
-
85
- return this;
86
- }
87
-
88
- public delete(
89
- attrs: Partial<Record<keyof T, Set<NativeAttributeValue>>>,
90
- ): this {
91
- this.actions.delete = { ...this.actions.delete, ...attrs };
92
- return this;
93
- }
94
-
95
- /**
96
- * Adds a condition expression to the update.
97
- */
98
- public setCondition(
99
- expression: string,
100
- attributeValues: Record<string, NativeAttributeValue>,
101
- attributeNames: Record<string, string>,
102
- ): this {
103
- if (this.condition) {
104
- // Merge conditions with AND.
105
- this.condition.expression += ` AND ${expression}`;
106
- Object.assign(this.condition.attributeValues, attributeValues);
107
- Object.assign(this.condition.attributeNames, attributeNames);
108
- } else {
109
- this.condition = {
110
- expression,
111
- attributeValues,
112
- attributeNames,
113
- };
114
- }
115
- return this;
116
- }
117
-
118
- /**
119
- * Specifies additional transaction items to include when executing this update as a transaction.
120
- */
121
- public transactWrite(ops: TransactWriteItem[] | TransactWriteItem): this {
122
- if (Array.isArray(ops)) {
123
- this.extraTransactItems.push(...ops);
124
- } else {
125
- this.extraTransactItems.push(ops);
126
- }
127
- return this;
128
- }
129
-
130
- /**
131
- * Builds the update expression and associated maps.
132
- */
133
- private buildExpression(newItemForIndexes?: T): {
134
- updateExpression: string;
135
- attributeNames: Record<string, string>;
136
- attributeValues?: Record<string, NativeAttributeValue>;
137
- } {
138
- const ExpressionAttributeNames: Record<string, string> = {};
139
- const ExpressionAttributeValues: Record<string, NativeAttributeValue> = {};
140
- const clauses: string[] = [];
141
-
142
- // 1) SET – from actions.set
143
- const setParts: string[] = [];
144
- if (this.actions.set) {
145
- for (const [attr, value] of Object.entries(this.actions.set)) {
146
- const nameKey = `#n_${attr}`;
147
- const valueKey = `:v_${attr}`;
148
- ExpressionAttributeNames[nameKey] = attr;
149
- ExpressionAttributeValues[valueKey] = value!;
150
- setParts.push(`${nameKey} = ${valueKey}`);
151
- }
152
- }
153
-
154
- // 2) also SET – from index‐rebuild if requested
155
- if (newItemForIndexes) {
156
- const indexAttrs = this.parent.buildIndexes(newItemForIndexes);
157
- for (const [attr, value] of Object.entries(indexAttrs)) {
158
- const nameKey = `#n_idx_${attr}`;
159
- const valueKey = `:v_idx_${attr}`;
160
- ExpressionAttributeNames[nameKey] = attr;
161
- ExpressionAttributeValues[valueKey] = value;
162
- setParts.push(`${nameKey} = ${valueKey}`);
163
- }
164
- }
165
- if (setParts.length > 0) {
166
- clauses.push(`SET ${setParts.join(", ")}`);
167
- }
168
-
169
- // 3) REMOVE
170
- if (this.actions.remove?.length) {
171
- const removeParts = this.actions.remove.map((attr) => {
172
- const nameKey = `#n_${String(attr)}`;
173
- ExpressionAttributeNames[nameKey] = String(attr);
174
- return nameKey;
175
- });
176
- clauses.push(`REMOVE ${removeParts.join(", ")}`);
177
- }
178
-
179
- // 4) ADD
180
- if (this.actions.add) {
181
- const addParts: string[] = [];
182
- for (const [attr, value] of Object.entries(this.actions.add)) {
183
- const nameKey = `#n_${attr}`;
184
- const valueKey = `:v_${attr}`;
185
- ExpressionAttributeNames[nameKey] = attr;
186
- ExpressionAttributeValues[valueKey] = value as NativeAttributeValue;
187
- addParts.push(`${nameKey} ${valueKey}`);
188
- }
189
- if (addParts.length) {
190
- clauses.push(`ADD ${addParts.join(", ")}`);
191
- }
192
- }
193
-
194
- // 5) DELETE
195
- if (this.actions.delete) {
196
- const deleteParts: string[] = [];
197
- for (const [attr, value] of Object.entries(this.actions.delete)) {
198
- const nameKey = `#n_${attr}`;
199
- const valueKey = `:v_${attr}`;
200
- ExpressionAttributeNames[nameKey] = attr;
201
- ExpressionAttributeValues[valueKey] = value as NativeAttributeValue;
202
- deleteParts.push(`${nameKey} ${valueKey}`);
203
- }
204
- if (deleteParts.length) {
205
- clauses.push(`DELETE ${deleteParts.join(", ")}`);
206
- }
207
- }
208
-
209
- // 6) merge in condition‐names/values
210
- if (this.condition) {
211
- Object.assign(ExpressionAttributeNames, this.condition.attributeNames);
212
- Object.assign(ExpressionAttributeValues, this.condition.attributeValues);
213
- }
214
-
215
- // 7) normalize empty values
216
- const hasValues = Object.keys(ExpressionAttributeValues).length > 0;
217
- const finalValues = hasValues ? ExpressionAttributeValues : undefined;
218
-
219
- if (clauses.length === 0) {
220
- throw new Error(
221
- "No attributes to update – all values were empty or undefined",
222
- );
223
- }
224
-
225
- return {
226
- updateExpression: clauses.join(" "),
227
- attributeNames: ExpressionAttributeNames,
228
- attributeValues: finalValues,
229
- };
230
- }
231
-
232
- /**
233
- * Returns a transaction update item that can be included in a transactWrite call.
234
- */
235
- public async toTransactUpdate(
236
- newItemForIndexes?: T,
237
- ): Promise<TransactWriteItem> {
238
- if (!newItemForIndexes) {
239
- newItemForIndexes = await this.createExpectedNewItem();
240
- }
241
- const { updateExpression, attributeNames, attributeValues } =
242
- this.buildExpression(newItemForIndexes);
243
- const updateItem: Update = {
244
- TableName: this.parent.getTableName(),
245
- Key: this.parent.buildKey(this.key),
246
- UpdateExpression: updateExpression,
247
- ExpressionAttributeNames: attributeNames,
248
- ExpressionAttributeValues: attributeValues,
249
- };
250
- if (this.condition?.expression) {
251
- updateItem.ConditionExpression = this.condition.expression;
252
- }
253
- return { Update: updateItem };
254
- }
255
-
256
- private async createExpectedNewItem() {
257
- const existingItem = await this.parent.get(this.key).execute();
258
- if (existingItem === null) {
259
- throw new Error("Item not found");
260
- }
261
- const expectedNewItem: Record<string, any> = {
262
- ...existingItem,
263
- ...this.actions.set,
264
- };
265
- if (this.actions.remove) {
266
- this.actions.remove.forEach((attr) => {
267
- delete expectedNewItem[String(attr)];
268
- });
269
- }
270
- if (this.actions.add) {
271
- Object.entries(this.actions.add).forEach(([attr, value]) => {
272
- const currentValue = expectedNewItem[attr] ?? 0;
273
- if (typeof value === "number") {
274
- expectedNewItem[attr] = currentValue + value;
275
- } else if (value instanceof Set) {
276
- const currentSet =
277
- expectedNewItem[attr] instanceof Set
278
- ? expectedNewItem[attr]
279
- : new Set();
280
- expectedNewItem[attr] = new Set([...currentSet, ...value]);
281
- }
282
- });
283
- }
284
- if (this.actions.delete) {
285
- Object.entries(this.actions.delete).forEach(([attr, value]) => {
286
- if (value instanceof Set) {
287
- const currentSet = expectedNewItem[attr];
288
- if (currentSet instanceof Set) {
289
- value.forEach((v) => {
290
- currentSet.delete(v);
291
- });
292
- }
293
- }
294
- });
295
- }
296
- return this.parent.getSchema().parse(expectedNewItem) as T;
297
- }
298
-
299
- /**
300
- * Commits the update immediately by calling the parent's update method.
301
- */
302
- public async execute(): Promise<T> {
303
- const expectedNewItem = await this.createExpectedNewItem();
304
-
305
- if (this.parent.getTimestamps()) {
306
- const now = new Date().toISOString();
307
- if (!this.actions.set) {
308
- this.actions.set = {};
309
- }
310
- this.actions.set = { ...this.actions.set, updatedAt: now };
311
- }
312
- if (this.extraTransactItems.length > 0) {
313
- // For transactions, we must throw if there's nothing to update
314
- // since we can't safely skip updates in a transaction
315
- const myTransactItem = await this.toTransactUpdate(expectedNewItem);
316
- const allItems = [...this.extraTransactItems, myTransactItem];
317
- await this.parent.getClient().send(
318
- new TransactWriteCommand({
319
- TransactItems: allItems,
320
- }),
321
- );
322
- // After transaction, retrieve the updated item.
323
- const result = await this.parent.get(this.key).execute();
324
- if (result === null) {
325
- throw new Error("Item not found after transaction update");
326
- }
327
-
328
- return result;
329
- }
330
-
331
- // For normal updates, handle empty updates gracefully
332
- try {
333
- const { updateExpression, attributeNames, attributeValues } =
334
- this.buildExpression(expectedNewItem);
335
-
336
- let params: UpdateCommandInput = {
337
- TableName: this.parent.getTableName(),
338
- Key: this.parent.buildKey(this.key),
339
- UpdateExpression: updateExpression,
340
- ExpressionAttributeNames: attributeNames,
341
- ExpressionAttributeValues: attributeValues,
342
- ReturnValues: "ALL_NEW" as ReturnValue,
343
- };
344
-
345
- if (this.condition?.expression) {
346
- params.ConditionExpression = this.condition.expression;
347
- }
348
- const result = await this.parent
349
- .getClient()
350
- .send(new UpdateCommand(params));
351
- if (!result.Attributes) {
352
- throw new Error("No attributes returned after update");
353
- }
354
- return this.parent.getSchema().parse(result.Attributes) as T;
355
- } catch (error) {
356
- // If there's nothing to update, just return the existing item
357
- if (
358
- error instanceof Error &&
359
- error.message ===
360
- "No attributes to update - all values were empty or undefined"
361
- ) {
362
- const existingItem = await this.parent.get(this.key).execute();
363
- if (existingItem === null) {
364
- throw new Error("Item not found");
365
- }
366
- return existingItem;
367
- }
368
- throw error;
369
- }
370
- }
371
- }
package/src/operator.ts DELETED
@@ -1,43 +0,0 @@
1
- export type Operator =
2
- | "=="
3
- | "!="
4
- | "<"
5
- | "<="
6
- | ">"
7
- | ">="
8
- | "begins_with"
9
- | "between"
10
- | "contains";
11
-
12
- export function getOperatorExpression(
13
- operator: Operator,
14
- nameKey: string,
15
- valueKey: string,
16
- secondValueKey?: string,
17
- ): string {
18
- switch (operator) {
19
- case "==":
20
- return `${nameKey} = ${valueKey}`;
21
- case "!=":
22
- return `${nameKey} <> ${valueKey}`;
23
- case "<":
24
- return `${nameKey} < ${valueKey}`;
25
- case "<=":
26
- return `${nameKey} <= ${valueKey}`;
27
- case ">":
28
- return `${nameKey} > ${valueKey}`;
29
- case ">=":
30
- return `${nameKey} >= ${valueKey}`;
31
- case "begins_with":
32
- return `begins_with(${nameKey}, ${valueKey})`;
33
- case "between":
34
- if (!secondValueKey) {
35
- throw new Error("The 'between' operator requires two value keys");
36
- }
37
- return `${nameKey} BETWEEN ${valueKey} AND ${secondValueKey}`;
38
- case "contains":
39
- return `contains(${nameKey}, ${valueKey})`;
40
- default:
41
- throw new Error("Unsupported operator");
42
- }
43
- }
@@ -1,6 +0,0 @@
1
- import { type NativeAttributeValue } from "@aws-sdk/lib-dynamodb";
2
-
3
- export type PaginatedResult<T> = {
4
- items: T[];
5
- lastKey: Record<string, NativeAttributeValue> | undefined;
6
- };
@@ -1,122 +0,0 @@
1
- import { z } from "zod";
2
- import { BetterDDB } from "../src/betterddb";
3
- import { createTestTable, deleteTestTable } from "./utils/table-setup";
4
- import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
5
- import { DynamoDB, GlobalSecondaryIndex } from "@aws-sdk/client-dynamodb";
6
- import {
7
- KeySchemaElement,
8
- AttributeDefinition,
9
- } from "@aws-sdk/client-dynamodb";
10
- const TEST_TABLE = "batch-get-test-table";
11
- const ENDPOINT = "http://localhost:4566";
12
- const REGION = "us-east-1";
13
- const ENTITY_TYPE = "USER";
14
- const PRIMARY_KEY = "pk";
15
- const PRIMARY_KEY_TYPE = "S";
16
- const SORT_KEY = "sk";
17
- const SORT_KEY_TYPE = "S";
18
- const GSI_NAME = "EmailIndex";
19
- const GSI_PRIMARY_KEY = "gsi1pk";
20
- const GSI_SORT_KEY = "gsi1sk";
21
- const KEY_SCHEMA = [
22
- { AttributeName: PRIMARY_KEY, KeyType: "HASH" },
23
- { AttributeName: SORT_KEY, KeyType: "RANGE" },
24
- ] as KeySchemaElement[];
25
- const ATTRIBUTE_DEFINITIONS = [
26
- { AttributeName: PRIMARY_KEY, AttributeType: PRIMARY_KEY_TYPE },
27
- { AttributeName: SORT_KEY, AttributeType: SORT_KEY_TYPE },
28
- { AttributeName: GSI_PRIMARY_KEY, AttributeType: PRIMARY_KEY_TYPE },
29
- { AttributeName: GSI_SORT_KEY, AttributeType: SORT_KEY_TYPE },
30
- ] as AttributeDefinition[];
31
- const GSIS = [
32
- {
33
- IndexName: GSI_NAME,
34
- KeySchema: [
35
- { AttributeName: GSI_PRIMARY_KEY, KeyType: "HASH" },
36
- { AttributeName: GSI_SORT_KEY, KeyType: "RANGE" },
37
- ],
38
- Projection: {
39
- ProjectionType: "ALL",
40
- },
41
- },
42
- ] as GlobalSecondaryIndex[];
43
- const client = DynamoDBDocumentClient.from(
44
- new DynamoDB({
45
- region: REGION,
46
- endpoint: ENDPOINT,
47
- }),
48
- );
49
-
50
- const UserSchema = z.object({
51
- id: z.string(),
52
- name: z.string(),
53
- email: z.string().email(),
54
- });
55
-
56
- type User = z.infer<typeof UserSchema>;
57
-
58
- const userDdb = new BetterDDB<User>({
59
- schema: UserSchema,
60
- tableName: TEST_TABLE,
61
- entityType: ENTITY_TYPE,
62
- keys: {
63
- primary: { name: PRIMARY_KEY, definition: { build: (raw) => raw.id! } },
64
- sort: { name: SORT_KEY, definition: { build: (raw) => raw.email! } },
65
- },
66
- client,
67
- timestamps: true,
68
- });
69
-
70
- beforeAll(async () => {
71
- await createTestTable(TEST_TABLE, KEY_SCHEMA, ATTRIBUTE_DEFINITIONS, GSIS);
72
- await userDdb
73
- .create({ id: "user-123", name: "John Doe", email: "john@example.com" })
74
- .execute();
75
- await userDdb
76
- .create({ id: "user-124", name: "John Doe", email: "john@example.com" })
77
- .execute();
78
- await userDdb
79
- .create({ id: "user-125", name: "Bob Doe", email: "bob@example.com" })
80
- .execute();
81
- });
82
-
83
- afterAll(async () => {
84
- await deleteTestTable(TEST_TABLE);
85
- });
86
-
87
- describe("BetterDDB - Get Operation", () => {
88
- it("should retrieve an item using GetBuilder", async () => {
89
- const users = await userDdb
90
- .batchGet([
91
- { id: "user-123", email: "john@example.com" },
92
- { id: "user-124", email: "john@example.com" },
93
- ])
94
- .execute();
95
- expect(users.length).toEqual(2);
96
- expect(users.some((user) => user.id === "user-123")).toBe(true);
97
- expect(users.some((user) => user.id === "user-124")).toBe(true);
98
- });
99
-
100
- it("should retrieve an item using GetBuilder that does not exist", async () => {
101
- const users = await userDdb
102
- .batchGet([{ id: "user-123", email: "jane@example.com" }])
103
- .execute();
104
- expect(users.length).toEqual(0);
105
- });
106
-
107
- it("should return an empty array if no keys are provided", async () => {
108
- const users = await userDdb.batchGet([]).execute();
109
- expect(users.length).toEqual(0);
110
- });
111
-
112
- it("should deduplicate keys", async () => {
113
- const users = await userDdb
114
- .batchGet([
115
- { id: "user-123", email: "john@example.com" },
116
- { id: "user-123", email: "john@example.com" },
117
- ])
118
- .execute();
119
- expect(users.length).toEqual(1);
120
- expect(users[0].id).toEqual("user-123");
121
- });
122
- });
@@ -1,121 +0,0 @@
1
- import { z } from "zod";
2
- import { BetterDDB } from "../src/betterddb";
3
- import { createTestTable, deleteTestTable } from "./utils/table-setup";
4
- import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
5
- import { DynamoDB, GlobalSecondaryIndex } from "@aws-sdk/client-dynamodb";
6
- import { GetCommand } from "@aws-sdk/lib-dynamodb";
7
- import {
8
- KeySchemaElement,
9
- AttributeDefinition,
10
- } from "@aws-sdk/client-dynamodb";
11
- const TEST_TABLE = "create-test-table";
12
- const ENDPOINT = "http://localhost:4566";
13
- const REGION = "us-east-1";
14
- const ENTITY_TYPE = "USER";
15
- const PRIMARY_KEY = "pk";
16
- const PRIMARY_KEY_TYPE = "S";
17
- const SORT_KEY = "sk";
18
- const SORT_KEY_TYPE = "S";
19
- const GSI_NAME = "EmailIndex";
20
- const GSI_PRIMARY_KEY = "gsi1pk";
21
- const GSI_SORT_KEY = "gsi1sk";
22
- const KEY_SCHEMA = [
23
- { AttributeName: PRIMARY_KEY, KeyType: "HASH" },
24
- { AttributeName: SORT_KEY, KeyType: "RANGE" },
25
- ] as KeySchemaElement[];
26
- const ATTRIBUTE_DEFINITIONS = [
27
- { AttributeName: PRIMARY_KEY, AttributeType: PRIMARY_KEY_TYPE },
28
- { AttributeName: SORT_KEY, AttributeType: SORT_KEY_TYPE },
29
- { AttributeName: GSI_PRIMARY_KEY, AttributeType: PRIMARY_KEY_TYPE },
30
- { AttributeName: GSI_SORT_KEY, AttributeType: SORT_KEY_TYPE },
31
- ] as AttributeDefinition[];
32
- const GSIS = [
33
- {
34
- IndexName: GSI_NAME,
35
- KeySchema: [
36
- { AttributeName: GSI_PRIMARY_KEY, KeyType: "HASH" },
37
- { AttributeName: GSI_SORT_KEY, KeyType: "RANGE" },
38
- ],
39
- Projection: {
40
- ProjectionType: "ALL",
41
- },
42
- },
43
- ] as GlobalSecondaryIndex[];
44
- const client = DynamoDBDocumentClient.from(
45
- new DynamoDB({
46
- region: REGION,
47
- endpoint: ENDPOINT,
48
- }),
49
- );
50
-
51
- const UserSchema = z.object({
52
- id: z.string(),
53
- name: z.string(),
54
- email: z.string().email(),
55
- });
56
-
57
- type User = z.infer<typeof UserSchema>;
58
-
59
- const userDdb = new BetterDDB<User>({
60
- schema: UserSchema,
61
- tableName: TEST_TABLE,
62
- entityType: ENTITY_TYPE,
63
- keys: {
64
- primary: { name: "pk", definition: { build: (raw) => `USER#${raw.id}` } },
65
- sort: { name: "sk", definition: { build: (raw) => `EMAIL#${raw.email}` } },
66
- gsis: {
67
- gsi1: {
68
- name: "gsi1",
69
- primary: { name: "gsi1pk", definition: { build: (raw) => "NAME" } },
70
- sort: {
71
- name: "gsi1sk",
72
- definition: { build: (raw) => `NAME#${raw.name}` },
73
- },
74
- },
75
- },
76
- },
77
- client,
78
- timestamps: true,
79
- });
80
-
81
- beforeAll(async () => {
82
- await createTestTable(TEST_TABLE, KEY_SCHEMA, ATTRIBUTE_DEFINITIONS, GSIS);
83
- });
84
-
85
- afterAll(async () => {
86
- await deleteTestTable(TEST_TABLE);
87
- });
88
-
89
- describe("BetterDDB - Create Operation", () => {
90
- it("should insert an item using CreateBuilder", async () => {
91
- const user = {
92
- id: "user-123",
93
- name: "John Doe",
94
- email: "john@example.com",
95
- };
96
-
97
- await userDdb.create(user).execute();
98
-
99
- const result = await client.send(
100
- new GetCommand({
101
- TableName: TEST_TABLE,
102
- Key: { pk: "USER#user-123", sk: "EMAIL#john@example.com" },
103
- }),
104
- );
105
-
106
- expect(result).not.toBeNull();
107
- expect(result.Item).not.toBeNull();
108
- expect(result.Item?.pk).toBe("USER#user-123");
109
- expect(result.Item?.sk).toBe("EMAIL#john@example.com");
110
- expect(result.Item?.gsi1pk).toBe("NAME");
111
- expect(result.Item?.gsi1sk).toBe("NAME#John Doe");
112
- expect(result.Item?.id).toBe("user-123");
113
- expect(result.Item?.createdAt).not.toBeNull();
114
- expect(result.Item?.updatedAt).not.toBeNull();
115
- });
116
-
117
- it("should fails to validate and not insert an item", async () => {
118
- const user = { id: "user-123", email: "john@example.com" } as User;
119
- await expect(userDdb.create(user).execute()).rejects.toThrow();
120
- });
121
- });