dynamo-bao 0.1.0

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.
@@ -0,0 +1,428 @@
1
+ const path = require("path");
2
+ const fs = require("fs");
3
+ const { createLogger } = require("../utils/scriptLogger");
4
+ const logger = createLogger("ModelGen");
5
+
6
+ const codeGenPrefix = ""; // "cg";
7
+
8
+ function generateModelClass(
9
+ modelName,
10
+ modelConfig,
11
+ allModels,
12
+ fieldResolver,
13
+ outputDir,
14
+ ) {
15
+ if (!modelConfig || !modelConfig.fields) {
16
+ throw new Error(
17
+ `Invalid model configuration for ${modelName}: missing fields`,
18
+ );
19
+ }
20
+
21
+ // Track which fields, constants, and models are actually used
22
+ const usedFields = new Set();
23
+ const customFields = new Set();
24
+ const baseImports = new Set(["BaoModel"]);
25
+ const constantImports = new Set();
26
+
27
+ console.log("model config", modelConfig);
28
+
29
+ // Generate fields and track used field types
30
+ const fields = Object.entries(modelConfig.fields)
31
+ .map(([fieldName, fieldConfig]) => {
32
+ // Verify the field exists before using it
33
+ const fieldClass = fieldResolver.getFieldDefinition(fieldConfig.type);
34
+ if (!fieldClass) {
35
+ throw new Error(
36
+ `Field type '${fieldConfig.type}' not found for ${modelName}.${fieldName}`,
37
+ );
38
+ }
39
+
40
+ // Track if this is a built-in or custom field
41
+ if (fieldResolver.isCustomField(fieldConfig.type)) {
42
+ customFields.add(fieldConfig.type);
43
+ } else {
44
+ usedFields.add(fieldConfig.type);
45
+ }
46
+
47
+ if (fieldConfig.type === "RelatedField") {
48
+ return ` ${fieldName}: ${fieldConfig.type}('${fieldConfig.model}', { required: ${!!fieldConfig.required} }),`;
49
+ }
50
+
51
+ // Build options object from all field config properties except 'type'
52
+ const options = Object.entries(fieldConfig)
53
+ .filter(([key]) => key !== "type")
54
+ .map(([key, value]) => {
55
+ // Handle different types of values
56
+ if (typeof value === "string") return `${key}: '${value}'`;
57
+ if (Array.isArray(value)) return `${key}: ${JSON.stringify(value)}`;
58
+ return `${key}: ${value}`;
59
+ });
60
+
61
+ const optionsStr = options.length ? `{ ${options.join(", ")} }` : "";
62
+ return ` ${fieldName}: ${fieldConfig.type}(${optionsStr}),`;
63
+ })
64
+ .join("\n");
65
+
66
+ // Handle primary key configuration
67
+ const partitionKey = modelConfig.primaryKey.partitionKey;
68
+ const sortKey = modelConfig.primaryKey.sortKey || "modelPrefix";
69
+ logger.debug(`Generating primary key for ${modelName}:`, {
70
+ partitionKey,
71
+ sortKey,
72
+ });
73
+ const primaryKeyConfig = `PrimaryKeyConfig('${partitionKey}', '${sortKey}')`;
74
+
75
+ // Generate indexes and track used constants
76
+ const indexes = modelConfig.indexes
77
+ ? Object.entries(modelConfig.indexes)
78
+ .map(([indexName, indexConfig]) => {
79
+ if (indexConfig === "primaryKey") {
80
+ return ` ${indexName}: this.primaryKey,`;
81
+ }
82
+
83
+ // Update logging
84
+ logger.debug(`Generating index ${indexName}:`, indexConfig);
85
+
86
+ const indexId = `GSI_INDEX_ID${indexConfig.indexId.slice(-1)}`;
87
+ constantImports.add(indexId);
88
+ return ` ${indexName}: IndexConfig('${indexConfig.partitionKey}', '${indexConfig.sortKey}', ${indexId}),`;
89
+ })
90
+ .join("\n")
91
+ : "";
92
+
93
+ // Generate unique constraints and track used constants
94
+ const uniqueConstraints = modelConfig.uniqueConstraints
95
+ ? Object.entries(modelConfig.uniqueConstraints)
96
+ .map(([constraintName, constraintConfig]) => {
97
+ const constraintId = `UNIQUE_CONSTRAINT_ID${constraintConfig.uniqueConstraintId.slice(-1)}`;
98
+ constantImports.add(constraintId);
99
+ return ` ${constraintName}: UniqueConstraintConfig('${constraintConfig.field}', ${constraintId}),`;
100
+ })
101
+ .join("\n")
102
+ : "";
103
+
104
+ // Always need these
105
+ baseImports.add("PrimaryKeyConfig");
106
+ if (indexes) baseImports.add("IndexConfig");
107
+ if (uniqueConstraints) baseImports.add("UniqueConstraintConfig");
108
+
109
+ // Generate query methods and get related models
110
+ const { methods: queryMethods, relatedModels } = generateQueryMethods(
111
+ modelName,
112
+ modelConfig,
113
+ allModels,
114
+ );
115
+ const uniqueConstraintMethods = generateUniqueConstraintMethods(modelConfig);
116
+ const relatedFieldMethods = generateRelatedFieldMethods(modelConfig.fields);
117
+
118
+ // Generate import statements
119
+ const baseImportStr = Array.from(baseImports).join(",\n ");
120
+ const constantImportStr = Array.from(constantImports).join(",\n ");
121
+ const fieldImports = Array.from(usedFields).join(",\n ");
122
+
123
+ logger.debug("fieldResolver customFields", fieldResolver.customFieldsPath);
124
+
125
+ // get relative path for fieldResolver.customFieldsPath from projectPath
126
+ const relativePath = path.relative(outputDir, fieldResolver.customFieldsPath);
127
+ logger.debug("relativePath", relativePath);
128
+
129
+ // Generate custom field imports
130
+ const customFieldImports = Array.from(customFields)
131
+ .map((fieldType) => {
132
+ // Remove 'Field' suffix before converting to kebab case
133
+ const baseName = fieldType.replace(/Field$/, "");
134
+ const kebabName = baseName
135
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
136
+ .toLowerCase();
137
+ return `const { ${fieldType} } = require('${relativePath}/${kebabName}-field');`;
138
+ })
139
+ .join("\n");
140
+
141
+ // Generate the final code with separated imports
142
+ return `// 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨
143
+ // DO NOT EDIT: Generated by model-codegen
144
+ // 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨
145
+ const {
146
+ ${baseImportStr}
147
+ } = require('dynamo-bao');
148
+
149
+ ${
150
+ constantImports.size > 0
151
+ ? `const {
152
+ ${constantImportStr}
153
+ } = require('dynamo-bao').constants;
154
+
155
+ `
156
+ : ""
157
+ }
158
+ ${
159
+ usedFields.size > 0
160
+ ? `const {
161
+ ${fieldImports}
162
+ } = require('dynamo-bao').fields;
163
+
164
+ `
165
+ : ""
166
+ }
167
+ ${customFieldImports}
168
+
169
+ ${Array.from(relatedModels)
170
+ .map((model) => {
171
+ const kebabName = model
172
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
173
+ .toLowerCase();
174
+ return `const { ${model} } = require('./${kebabName}');`;
175
+ })
176
+ .join("\n")}
177
+
178
+ class ${modelName} extends BaoModel {
179
+ static modelPrefix = '${modelConfig.modelPrefix}';
180
+
181
+ static fields = {
182
+ ${fields}
183
+ };
184
+
185
+ static primaryKey = ${primaryKeyConfig};
186
+ ${indexes ? `\n static indexes = {\n${indexes}\n };` : ""}
187
+ ${uniqueConstraints ? `\n static uniqueConstraints = {\n${uniqueConstraints}\n };` : ""}
188
+ ${queryMethods}
189
+ ${uniqueConstraintMethods}
190
+ ${relatedFieldMethods}
191
+ }
192
+
193
+ module.exports = { ${modelName} };
194
+ `;
195
+ }
196
+
197
+ function generateUniqueConstraintMethods(modelConfig) {
198
+ if (!modelConfig.uniqueConstraints) return "";
199
+
200
+ return Object.entries(modelConfig.uniqueConstraints)
201
+ .map(([name, constraint]) => {
202
+ const methodName = `${codeGenPrefix}findBy${name.replace(/^unique/, "")}`;
203
+ return `
204
+ static async ${methodName}(value) {
205
+ return await this.findByUniqueConstraint('${name}', value);
206
+ }`;
207
+ })
208
+ .join("\n");
209
+ }
210
+
211
+ function generateModelFiles(models, outputDir, fieldResolver) {
212
+ if (!fs.existsSync(outputDir)) {
213
+ fs.mkdirSync(outputDir, { recursive: true });
214
+ }
215
+
216
+ Object.entries(models).forEach(([modelName, modelConfig]) => {
217
+ // Convert model name from PascalCase to kebab-case for the file name
218
+ const fileName = modelName
219
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
220
+ .toLowerCase();
221
+
222
+ const filePath = path.join(outputDir, `${fileName}.js`);
223
+
224
+ // delete the file if it exists
225
+ if (fs.existsSync(filePath)) {
226
+ fs.unlinkSync(filePath);
227
+ }
228
+
229
+ const code = generateModelClass(
230
+ modelName,
231
+ modelConfig,
232
+ models,
233
+ fieldResolver,
234
+ outputDir,
235
+ );
236
+
237
+ fs.writeFileSync(filePath, code);
238
+ console.log(`Generated ${filePath}`);
239
+ });
240
+ }
241
+
242
+ function generateQueryMethods(modelName, modelConfig, allModels) {
243
+ let methods = "";
244
+ const relatedModels = new Set();
245
+
246
+ // First, generate methods for indexes that use modelPrefix (self-referential queries)
247
+ if (modelConfig.indexes) {
248
+ Object.entries(modelConfig.indexes).forEach(([indexName, index]) => {
249
+ if (index !== "primaryKey" && index.partitionKey === "modelPrefix") {
250
+ let methodName;
251
+ if (indexName.includes("For")) {
252
+ const [prefix] = indexName.split("For");
253
+ methodName = `${codeGenPrefix}query${prefix.charAt(0).toUpperCase()}${prefix.slice(1)}`;
254
+ } else {
255
+ methodName = `${codeGenPrefix}query${indexName.charAt(0).toUpperCase()}${indexName.slice(1)}`;
256
+ }
257
+
258
+ methods += `
259
+ static async ${methodName}(skCondition = null, options = {}) {
260
+ const results = await this.queryByIndex(
261
+ '${indexName}',
262
+ this.modelPrefix,
263
+ skCondition,
264
+ options
265
+ );
266
+
267
+ return results;
268
+ }`;
269
+ }
270
+ });
271
+ }
272
+
273
+ // Then generate methods for other models that have relations to this model
274
+ Object.entries(allModels).forEach(([otherModelName, otherModel]) => {
275
+ if (otherModel.indexes) {
276
+ // First check if the primary key's partition key is a relation to our model
277
+ const pkPartitionField =
278
+ otherModel.fields[otherModel.primaryKey.partitionKey];
279
+ if (
280
+ pkPartitionField?.type === "RelatedField" &&
281
+ pkPartitionField.model === modelName &&
282
+ otherModel.tableType !== "mapping"
283
+ ) {
284
+ // Simple check here
285
+
286
+ relatedModels.add(otherModelName);
287
+
288
+ // Use the primary key index name if it exists in indexes
289
+ const primaryKeyIndexName =
290
+ Object.entries(otherModel.indexes).find(
291
+ ([_, index]) => index === "primaryKey",
292
+ )?.[0] || "primaryKey";
293
+
294
+ methods += `
295
+ async ${codeGenPrefix}query${otherModelName}s(skCondition = null, options = {}) {
296
+ const results = await ${otherModelName}.queryByIndex(
297
+ '${primaryKeyIndexName}',
298
+ this._getPkValue(),
299
+ skCondition,
300
+ options
301
+ );
302
+
303
+ return results;
304
+ }`;
305
+ }
306
+
307
+ // Then check other indexes
308
+ Object.entries(otherModel.indexes).forEach(([indexName, index]) => {
309
+ if (index === "primaryKey") return;
310
+
311
+ const pkField = otherModel.fields[index.partitionKey];
312
+
313
+ if (
314
+ pkField?.type === "RelatedField" &&
315
+ pkField.model === modelName &&
316
+ otherModel.tableType !== "mapping"
317
+ ) {
318
+ // Simple check here
319
+
320
+ relatedModels.add(otherModelName);
321
+
322
+ let methodName;
323
+ if (indexName.includes("For")) {
324
+ const [prefix] = indexName.split("For");
325
+ methodName = `${codeGenPrefix}query${prefix.charAt(0).toUpperCase()}${prefix.slice(1)}`;
326
+ } else {
327
+ methodName = `${codeGenPrefix}query${indexName.charAt(0).toUpperCase()}${indexName.slice(1)}`;
328
+ }
329
+
330
+ methods += `
331
+ async ${methodName}(skCondition = null, options = {}) {
332
+ const results = await ${otherModelName}.queryByIndex(
333
+ '${indexName}',
334
+ this._getPkValue(),
335
+ skCondition,
336
+ options
337
+ );
338
+
339
+ return results;
340
+ }`;
341
+ }
342
+ });
343
+ }
344
+ });
345
+
346
+ // Add mapping table helper methods
347
+ Object.entries(allModels).forEach(([mapModelName, mapModel]) => {
348
+ if (mapModel.indexes && mapModel.tableType === "mapping") {
349
+ // Only for mapping tables
350
+ Object.entries(mapModel.indexes).forEach(([indexName, index]) => {
351
+ let pkField, targetField;
352
+
353
+ if (index === "primaryKey") {
354
+ pkField = mapModel.fields[mapModel.primaryKey.partitionKey];
355
+ targetField = mapModel.fields[mapModel.primaryKey.sortKey];
356
+ } else if (index.partitionKey && index.sortKey) {
357
+ pkField = mapModel.fields[index.partitionKey];
358
+ targetField = mapModel.fields[index.sortKey];
359
+ }
360
+
361
+ // Check if this is a mapping table relationship
362
+ if (pkField?.type === "RelatedField" && pkField.model === modelName) {
363
+ relatedModels.add(mapModelName);
364
+
365
+ // Generate method name from index
366
+ let methodName;
367
+ if (indexName.includes("For")) {
368
+ const [prefix] = indexName.split("For");
369
+ methodName = `${codeGenPrefix}get${prefix.charAt(0).toUpperCase()}${prefix.slice(1)}`;
370
+ } else {
371
+ methodName = `${codeGenPrefix}get${indexName.charAt(0).toUpperCase()}${indexName.slice(1)}`;
372
+ }
373
+
374
+ // Find the "other" relation field that isn't the one we're querying with
375
+ const relationFields = Object.entries(mapModel.fields).filter(
376
+ ([_, field]) => field.type === "RelatedField",
377
+ );
378
+
379
+ const targetFieldName = relationFields.find(
380
+ ([_, field]) => field.model !== modelName,
381
+ )?.[0];
382
+
383
+ methods += `
384
+ async ${methodName}(mapSkCondition=null, limit=null, direction='ASC', startKey=null) {
385
+ return await ${mapModelName}.getRelatedObjectsViaMap(
386
+ "${indexName}",
387
+ this._getPkValue(),
388
+ "${targetFieldName}",
389
+ mapSkCondition,
390
+ limit,
391
+ direction,
392
+ startKey
393
+ );
394
+ }`;
395
+ }
396
+ });
397
+ }
398
+ });
399
+
400
+ return { methods, relatedModels };
401
+ }
402
+
403
+ // New function to generate related field getter methods
404
+ function generateRelatedFieldMethods(fields) {
405
+ if (!fields) return "";
406
+
407
+ const methods = [];
408
+
409
+ Object.entries(fields).forEach(([fieldName, fieldConfig]) => {
410
+ if (fieldConfig.type === "RelatedField") {
411
+ const baseName = fieldName.endsWith("Id")
412
+ ? fieldName.slice(0, -2)
413
+ : fieldName;
414
+
415
+ const capitalizedName =
416
+ baseName.charAt(0).toUpperCase() + baseName.slice(1);
417
+
418
+ methods.push(`
419
+ async ${codeGenPrefix}get${capitalizedName}() {
420
+ return await this.getOrLoadRelatedField('${fieldName}');
421
+ }`);
422
+ }
423
+ });
424
+
425
+ return methods.join("\n");
426
+ }
427
+
428
+ module.exports = { generateModelFiles };
@@ -0,0 +1,10 @@
1
+ const createLogger = (name) => {
2
+ return {
3
+ debug: (...args) => console.log(`[${name}]`, ...args),
4
+ info: (...args) => console.log(`[${name}]`, ...args),
5
+ warn: (...args) => console.warn(`[${name}]`, ...args),
6
+ error: (...args) => console.error(`[${name}]`, ...args),
7
+ };
8
+ };
9
+
10
+ module.exports = { createLogger };
package/bin/watch.js ADDED
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const chokidar = require("chokidar");
6
+ const { loadModelDefinitions } = require("./codegen");
7
+ const { generateModelFiles } = require("./generators/model");
8
+ const FieldResolver = require("../src/fieldResolver");
9
+ const { createLogger } = require("./utils/scriptLogger");
10
+
11
+ const logger = createLogger("Watch");
12
+
13
+ function loadConfig() {
14
+ const configPath = path.resolve(process.cwd(), "./config.js");
15
+ try {
16
+ return require(configPath);
17
+ } catch (error) {
18
+ console.error(
19
+ "Error loading config.js from current directory:",
20
+ error.message,
21
+ );
22
+ process.exit(1);
23
+ }
24
+ }
25
+
26
+ function generateModels(definitionsPath) {
27
+ const config = loadConfig();
28
+ console.log(`Generating models from: ${definitionsPath}`);
29
+ console.log(`Output directory: ${config.paths.modelsDir}`);
30
+ console.log(`Fields directory: ${config.paths.fieldsDir}`);
31
+
32
+ try {
33
+ const definitions = loadModelDefinitions(definitionsPath);
34
+ const builtInFieldsPath = path.resolve(__dirname, "../src/fields");
35
+ const customFieldsPath = config.paths.fieldsDir;
36
+
37
+ const fieldResolver = new FieldResolver(
38
+ builtInFieldsPath,
39
+ fs.existsSync(customFieldsPath) ? customFieldsPath : null,
40
+ );
41
+
42
+ generateModelFiles(
43
+ definitions.models,
44
+ config.paths.modelsDir,
45
+ fieldResolver,
46
+ );
47
+ logger.info("Models generated successfully");
48
+ } catch (error) {
49
+ logger.error("Error generating models:", error);
50
+ }
51
+ }
52
+
53
+ function getDefinitionsPath(config) {
54
+ if (config.paths.modelsDefinitionPath) {
55
+ const definitionPath = path.resolve(
56
+ process.cwd(),
57
+ config.paths.modelsDefinitionPath,
58
+ );
59
+ return definitionPath;
60
+ }
61
+ // Fall back to models.yaml in current directory
62
+ return path.resolve(process.cwd(), "./models.yaml");
63
+ }
64
+
65
+ function main() {
66
+ const config = loadConfig();
67
+ const definitionsPath = getDefinitionsPath(config);
68
+
69
+ // Initial generation
70
+ generateModels(definitionsPath);
71
+
72
+ // Set up watcher with appropriate glob pattern
73
+ const isDirectory = fs.statSync(definitionsPath).isDirectory();
74
+ const watchPattern = isDirectory
75
+ ? path.join(definitionsPath, "**/*.{yaml,yml}") // Watch all yaml files in directory
76
+ : definitionsPath; // Watch single file directly
77
+
78
+ const watcher = chokidar.watch(watchPattern, {
79
+ persistent: true,
80
+ ignoreInitial: true,
81
+ });
82
+
83
+ console.log(`Watching for changes in: ${watchPattern}`);
84
+
85
+ watcher
86
+ .on("change", (path) => generateModels(path))
87
+ .on("add", (path) => generateModels(path))
88
+ .on("error", (error) => console.error(`Watcher error: ${error}`));
89
+ }
90
+
91
+ if (require.main === module) {
92
+ main();
93
+ }
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "dynamo-bao",
3
+ "version": "0.1.0",
4
+ "description": "Simple powerful data modeleling primatives for DynamoDB in JavaScript",
5
+ "main": "src/index.js",
6
+ "scripts": {
7
+ "test": "LOG_LEVEL=OFF jest",
8
+ "test:debug": "LOG_LEVEL=DEBUG jest",
9
+ "create-table": "node bin/dynamo-bao-create-table.js",
10
+ "watch": "node bin/watch.js",
11
+ "docs": "jsdoc -c jsdoc.json --verbose"
12
+ },
13
+ "files": [
14
+ "bin/",
15
+ "src/",
16
+ "README.md"
17
+ ],
18
+ "keywords": [
19
+ "dynamodb",
20
+ "aws",
21
+ "database",
22
+ "orm",
23
+ "nosql",
24
+ "single-table-design"
25
+ ],
26
+ "author": "Adrian Graham",
27
+ "license": "MIT",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/adriangraham/dynamo-bao.git"
31
+ },
32
+ "dependencies": {
33
+ "@aws-sdk/client-dynamodb": "^3.521.0",
34
+ "@aws-sdk/lib-dynamodb": "^3.521.0",
35
+ "dotenv": "^16.4.7",
36
+ "js-yaml": "^4.1.0",
37
+ "ulid": "^2.3.0"
38
+ },
39
+ "devDependencies": {
40
+ "clean-jsdoc-theme": "^4.3.0",
41
+ "cross-env": "^7.0.3",
42
+ "docdash": "^2.0.2",
43
+ "gh-pages": "^6.2.0",
44
+ "jest": "^29.7.0",
45
+ "jsdoc": "^4.0.4",
46
+ "prettier": "3.4.2",
47
+ "serverless": "^3.38.0"
48
+ },
49
+ "bin": {
50
+ "bao-create-table": "bin/dynamo-bao-create-table.js",
51
+ "bao-codegen": "bin/codegen.js",
52
+ "bao-watch": "bin/watch.js"
53
+ }
54
+ }
package/src/config.js ADDED
@@ -0,0 +1,60 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const dotenv = require("dotenv");
4
+
5
+ function findConfig() {
6
+ const possibleNames = [
7
+ "config.js",
8
+ "dynamo-bao.config.js",
9
+ ".dynamo-bao/config.js",
10
+ ];
11
+ const searchPaths = [
12
+ process.cwd(), // Project root
13
+ // path.join(__dirname, '..'), // Library root
14
+ // path.join(__dirname, '../test'), // Library test directory
15
+ ];
16
+
17
+ // Search each directory for config files
18
+ for (const searchPath of searchPaths) {
19
+ for (const name of possibleNames) {
20
+ const configPath = path.join(searchPath, name);
21
+ if (fs.existsSync(configPath)) {
22
+ const rawConfig = require(configPath);
23
+ const configDir = path.dirname(configPath);
24
+
25
+ return {
26
+ ...rawConfig,
27
+ paths: {
28
+ ...rawConfig.paths,
29
+ modelsDir: rawConfig.paths.modelsDir
30
+ ? path.resolve(configDir, rawConfig.paths.modelsDir)
31
+ : null,
32
+ },
33
+ };
34
+ }
35
+ }
36
+ }
37
+
38
+ // If no config file found, create default config from env
39
+ dotenv.config();
40
+ return {
41
+ aws: {
42
+ region: process.env.AWS_REGION || "us-west-2",
43
+ },
44
+ db: {
45
+ tableName: process.env.TABLE_NAME || "dynamo-bao-dev",
46
+ },
47
+ logging: {
48
+ level: process.env.LOG_LEVEL || "ERROR",
49
+ },
50
+ paths: {
51
+ modelsDir: process.env.MODELS_DIR
52
+ ? path.resolve(process.cwd(), process.env.MODELS_DIR)
53
+ : null,
54
+ },
55
+ };
56
+ }
57
+
58
+ // Load config once at module level
59
+ const config = findConfig();
60
+ module.exports = config;
@@ -0,0 +1,35 @@
1
+ // Constants for GSI indexes
2
+ const GSI_INDEX_ID1 = "gsi1";
3
+ const GSI_INDEX_ID2 = "gsi2";
4
+ const GSI_INDEX_ID3 = "gsi3";
5
+
6
+ // Constants for unique constraints
7
+ const UNIQUE_CONSTRAINT_ID1 = "_uc1";
8
+ const UNIQUE_CONSTRAINT_ID2 = "_uc2";
9
+ const UNIQUE_CONSTRAINT_ID3 = "_uc3";
10
+
11
+ // Constants for system fields
12
+ const SYSTEM_FIELDS = [
13
+ "_pk",
14
+ "_sk",
15
+ "_gsi1_pk",
16
+ "_gsi1_sk",
17
+ "_gsi2_pk",
18
+ "_gsi2_sk",
19
+ "_gsi3_pk",
20
+ "_gsi3_sk",
21
+ "_gsi_test_id",
22
+ ];
23
+
24
+ const UNIQUE_CONSTRAINT_KEY = "_raft_uc";
25
+
26
+ module.exports = {
27
+ GSI_INDEX_ID1,
28
+ GSI_INDEX_ID2,
29
+ GSI_INDEX_ID3,
30
+ UNIQUE_CONSTRAINT_ID1,
31
+ UNIQUE_CONSTRAINT_ID2,
32
+ UNIQUE_CONSTRAINT_ID3,
33
+ SYSTEM_FIELDS,
34
+ UNIQUE_CONSTRAINT_KEY,
35
+ };
package/src/db.js ADDED
@@ -0,0 +1,21 @@
1
+ // src/db.js
2
+ const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
3
+ const { DynamoDBDocumentClient } = require("@aws-sdk/lib-dynamodb");
4
+
5
+ function createDbClient() {
6
+ const client = new DynamoDBClient({
7
+ region: process.env.AWS_REGION || "us-east-1",
8
+ maxAttempts: 3,
9
+ ...(process.env.DYNAMODB_ENDPOINT && {
10
+ endpoint: process.env.DYNAMODB_ENDPOINT,
11
+ }),
12
+ });
13
+
14
+ return DynamoDBDocumentClient.from(client, {
15
+ marshallOptions: {
16
+ removeUndefinedValues: true,
17
+ },
18
+ });
19
+ }
20
+
21
+ module.exports = { createDbClient };