dynamo-bao 0.1.2 → 0.1.4

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Adrian Graham
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # DynamoBao
2
2
 
3
+ [![GitHub stars](https://img.shields.io/github/stars/aag1024/dynamo-bao.svg?style=social&label=Star)](https://github.com/aag1024/dynamo-bao)
4
+ [![npm version](https://badge.fury.io/js/dynamo-bao.svg)](https://badge.fury.io/js/dynamo-bao)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
3
7
  DynamoBao is a simple lightweight library for building DynamoDB models in JavaScript. I've used
4
8
  DynamoDB for years and generally love it, but find getting started difficult and repetitive.
5
9
  DynamoBao is the tool I wish I had when I started.
@@ -155,7 +159,7 @@ npm install dynamo-bao
155
159
  Create a new Dynamo table for your project. You should have one table per project.
156
160
 
157
161
  ```
158
- npx bao-create-table
162
+ npx bao-init
159
163
  ```
160
164
 
161
165
  This creates a `config.js` which contains settings for your project like AWS region and the table name.
@@ -218,60 +222,56 @@ const { Post } = require("./models/post");
218
222
  const userConfig = require("./config");
219
223
  const dynamoBao = require("dynamo-bao");
220
224
  async function testUserModel() {
221
- try {
222
- dynamoBao.initModels(userConfig);
223
-
224
- // Find user by email
225
- const existingUser = await User.findByEmail("test@example.com");
226
- console.log("Found user by email:", existingUser.exists());
227
- if (existingUser.exists()) {
228
- await User.delete(existingUser.getPrimaryId());
229
- console.log("Deleted existing user");
230
- await new Promise((resolve) => setTimeout(resolve, 100)); // 100ms
231
- }
225
+ dynamoBao.initModels(userConfig);
232
226
 
233
- // Create a new user
234
- const user = new User({
235
- name: "Test User",
236
- email: "test@example.com",
237
- role: "user",
238
- profilePictureUrl: "https://example.com/profile.jpg",
239
- });
240
-
241
- await user.save();
242
- console.log("Created user:", user.getPrimaryId());
243
-
244
- // Find user by email
245
- const foundUser = await User.findByEmail("test@example.com");
246
- console.log("Found user by email:", foundUser.getPrimaryId());
247
-
248
- // Create some test posts for the user
249
- const post1 = new Post({
250
- userId: user.userId,
251
- title: "Test Post 1",
252
- content: "This is a test post",
253
- });
254
-
255
- const post2 = new Post({
256
- userId: user.userId,
257
- title: "Test Post 2",
258
- content: "This is another test post",
259
- });
260
-
261
- await Promise.all([post1.save(), post2.save()]);
262
-
263
- // Query user posts
264
- const userPosts = await user.queryPosts();
265
- console.log("User posts:", userPosts.items.length);
266
-
267
- // Or add a filter condition to the query
268
- const filteredPosts = await user.queryPosts(null, {
269
- filter: { content: { $contains: "another" } },
270
- });
271
- console.log("User posts matching filter:", filteredPosts.items.length);
272
- } catch (error) {
273
- console.error("Error:", error);
227
+ // Find user by email
228
+ const existingUser = await User.findByEmail("test@example.com");
229
+ console.log("Found user by email:", existingUser.exists());
230
+ if (existingUser.exists()) {
231
+ await User.delete(existingUser.getPrimaryId());
232
+ console.log("Deleted existing user");
233
+ await new Promise((resolve) => setTimeout(resolve, 100)); // 100ms
274
234
  }
235
+
236
+ // Create a new user
237
+ const user = new User({
238
+ name: "Test User",
239
+ email: "test@example.com",
240
+ role: "user",
241
+ profilePictureUrl: "https://example.com/profile.jpg",
242
+ });
243
+
244
+ await user.save();
245
+ console.log("Created user:", user.getPrimaryId());
246
+
247
+ // Find user by email
248
+ const foundUser = await User.findByEmail("test@example.com");
249
+ console.log("Found user by email:", foundUser.getPrimaryId());
250
+
251
+ // Create some test posts for the user
252
+ const post1 = new Post({
253
+ userId: user.userId,
254
+ title: "Test Post 1",
255
+ content: "This is a test post",
256
+ });
257
+
258
+ const post2 = new Post({
259
+ userId: user.userId,
260
+ title: "Test Post 2",
261
+ content: "This is another test post",
262
+ });
263
+
264
+ await Promise.all([post1.save(), post2.save()]);
265
+
266
+ // Query user posts
267
+ const userPosts = await user.queryPosts();
268
+ console.log("User posts:", userPosts.items.length);
269
+
270
+ // Or add a filter condition to the query
271
+ const filteredPosts = await user.queryPosts(null, {
272
+ filter: { content: { $contains: "another" } },
273
+ });
274
+ console.log("User posts matching filter:", filteredPosts.items.length);
275
275
  }
276
276
 
277
277
  // Run the test
package/bin/codegen.js CHANGED
@@ -7,24 +7,7 @@ const { generateModelFiles } = require("./generators/model");
7
7
  const { createLogger } = require("./utils/scriptLogger");
8
8
  const FieldResolver = require("../src/fieldResolver");
9
9
  const logger = createLogger("CodeGen");
10
-
11
- function loadConfig(definitionsPath) {
12
- try {
13
- // First try environment variable
14
- if (process.env.DYNAMO_BAO_CONFIG) {
15
- return require(
16
- path.resolve(process.cwd(), process.env.DYNAMO_BAO_CONFIG),
17
- );
18
- }
19
-
20
- // Then try config.js in the same directory as definitions
21
- const configPath = path.resolve(path.dirname(definitionsPath), "config.js");
22
- return require(configPath);
23
- } catch (err) {
24
- logger.debug("No config file found, using defaults");
25
- return {};
26
- }
27
- }
10
+ const config = require("../src/config");
28
11
 
29
12
  function loadModelDefinitions(definitionsPath, fieldResolver) {
30
13
  const models = {};
@@ -62,6 +45,23 @@ function loadModelDefinitions(definitionsPath, fieldResolver) {
62
45
  }
63
46
  }
64
47
 
48
+ // Process models to ensure mapping tables get both regular and mapping functions
49
+ for (const [modelName, modelDef] of Object.entries(models)) {
50
+ if (modelDef.mapping) {
51
+ // For mapping tables, merge mapping properties with regular model properties
52
+ models[modelName] = {
53
+ ...modelDef,
54
+ // Keep mapping specific properties
55
+ mapping: modelDef.mapping,
56
+ // Ensure other standard model properties are present
57
+ fields: modelDef.fields || {},
58
+ indexes: modelDef.indexes || {},
59
+ methods: modelDef.methods || {},
60
+ // Any other standard model properties you want to include
61
+ };
62
+ }
63
+ }
64
+
65
65
  logger.debug("Final merged models:", models);
66
66
  return { models, fieldResolver };
67
67
  }
@@ -69,9 +69,14 @@ function loadModelDefinitions(definitionsPath, fieldResolver) {
69
69
  function main() {
70
70
  const args = process.argv.slice(2);
71
71
 
72
- // Set default paths
73
- let definitionsPath = path.resolve(process.cwd(), "./models.yaml");
74
- let outputDir = path.resolve(process.cwd(), "./models");
72
+ // Set default paths, but prefer config paths if available
73
+ let definitionsPath = config?.paths?.modelsDefinitionPath
74
+ ? path.resolve(process.cwd(), config.paths.modelsDefinitionPath)
75
+ : path.resolve(process.cwd(), "./models.yaml");
76
+
77
+ let outputDir = config?.paths?.modelsDir
78
+ ? path.resolve(process.cwd(), config.paths.modelsDir)
79
+ : path.resolve(process.cwd(), "./models");
75
80
 
76
81
  // Override with command line arguments if provided
77
82
  if (args.length >= 1) {
@@ -83,9 +88,6 @@ function main() {
83
88
 
84
89
  console.log("codegen definitionsPath", definitionsPath);
85
90
  try {
86
- const config = loadConfig(definitionsPath);
87
- console.log("codegen config", config);
88
-
89
91
  // Built-in fields are in fields.js
90
92
  const builtInFieldsPath = path.resolve(__dirname, "../src/fields.js");
91
93
 
@@ -78,7 +78,7 @@ const config = {
78
78
  module.exports = config;
79
79
  `;
80
80
 
81
- const configPath = path.resolve(process.cwd(), "config.js");
81
+ const configPath = path.resolve(process.cwd(), "dynamo-bao.config.js");
82
82
  fs.writeFileSync(configPath, configContent);
83
83
  console.log(`Config file written to: ${configPath}`);
84
84
  }
@@ -172,7 +172,7 @@ async function createDirectoriesAndFiles() {
172
172
 
173
173
  // Create models.yaml with default content
174
174
  const modelsYamlPath = path.resolve(process.cwd(), "models.yaml");
175
- const yamlContent = `# Edit this file to create your models. For more information see: adriangraham.github.io/dynamo-bao/
175
+ const yamlContent = `# Edit this file to create your models. For more information see: aag1024.github.io/dynamo-bao/
176
176
  #
177
177
  # Here's a simple example:
178
178
  # models:
@@ -27,8 +27,17 @@ function generateModelClass(
27
27
  console.log("model config", modelConfig);
28
28
 
29
29
  // Generate fields and track used field types
30
- const fields = Object.entries(modelConfig.fields)
30
+ const fields = Object.entries(modelConfig.fields || {})
31
31
  .map(([fieldName, fieldConfig]) => {
32
+ // Special handling for mapping table fields
33
+ if (modelConfig.mapping && !fieldConfig.type) {
34
+ // Default to RelatedField if not specified in mapping table
35
+ fieldConfig = {
36
+ type: "RelatedField",
37
+ ...fieldConfig,
38
+ };
39
+ }
40
+
32
41
  // Verify the field exists before using it
33
42
  const fieldClass = fieldResolver.getFieldDefinition(fieldConfig.type);
34
43
  if (!fieldClass) {
@@ -138,6 +147,8 @@ function generateModelClass(
138
147
  })
139
148
  .join("\n");
140
149
 
150
+ const standardMethods = generateStandardModelMethods(modelConfig);
151
+
141
152
  // Generate the final code with separated imports
142
153
  return `// 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨 🧨
143
154
  // DO NOT EDIT: Generated by model-codegen
@@ -186,6 +197,7 @@ ${fields}
186
197
  ${indexes ? `\n static indexes = {\n${indexes}\n };` : ""}
187
198
  ${uniqueConstraints ? `\n static uniqueConstraints = {\n${uniqueConstraints}\n };` : ""}
188
199
  ${queryMethods}
200
+ ${standardMethods}
189
201
  ${uniqueConstraintMethods}
190
202
  ${relatedFieldMethods}
191
203
  }
@@ -278,8 +290,7 @@ function generateQueryMethods(modelName, modelConfig, allModels) {
278
290
  otherModel.fields[otherModel.primaryKey.partitionKey];
279
291
  if (
280
292
  pkPartitionField?.type === "RelatedField" &&
281
- pkPartitionField.model === modelName &&
282
- otherModel.tableType !== "mapping"
293
+ pkPartitionField.model === modelName
283
294
  ) {
284
295
  // Simple check here
285
296
 
@@ -310,11 +321,7 @@ function generateQueryMethods(modelName, modelConfig, allModels) {
310
321
 
311
322
  const pkField = otherModel.fields[index.partitionKey];
312
323
 
313
- if (
314
- pkField?.type === "RelatedField" &&
315
- pkField.model === modelName &&
316
- otherModel.tableType !== "mapping"
317
- ) {
324
+ if (pkField?.type === "RelatedField" && pkField.model === modelName) {
318
325
  // Simple check here
319
326
 
320
327
  relatedModels.add(otherModelName);
@@ -425,4 +432,23 @@ function generateRelatedFieldMethods(fields) {
425
432
  return methods.join("\n");
426
433
  }
427
434
 
435
+ function generateStandardModelMethods(modelConfig) {
436
+ let methods = "";
437
+
438
+ // Only add these methods if the model has standard fields
439
+ if (Object.keys(modelConfig.fields || {}).length > 0) {
440
+ methods += `
441
+ static async findAll(options = {}) {
442
+ return await this.scan(options);
443
+ }
444
+
445
+ static async findById(id) {
446
+ return await this.get(id);
447
+ }
448
+ `;
449
+ }
450
+
451
+ return methods;
452
+ }
453
+
428
454
  module.exports = { generateModelFiles };
package/bin/watch.js CHANGED
@@ -7,24 +7,23 @@ const { loadModelDefinitions } = require("./codegen");
7
7
  const { generateModelFiles } = require("./generators/model");
8
8
  const FieldResolver = require("../src/fieldResolver");
9
9
  const { createLogger } = require("./utils/scriptLogger");
10
+ const config = require("../src/config");
10
11
 
11
12
  const logger = createLogger("Watch");
12
13
 
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,
14
+ function getDefinitionsPath(config) {
15
+ if (config.paths.modelsDefinitionPath) {
16
+ const definitionPath = path.resolve(
17
+ process.cwd(),
18
+ config.paths.modelsDefinitionPath,
21
19
  );
22
- process.exit(1);
20
+ return definitionPath;
23
21
  }
22
+ // Fall back to models.yaml in current directory
23
+ return path.resolve(process.cwd(), "./models.yaml");
24
24
  }
25
25
 
26
26
  function generateModels(definitionsPath) {
27
- const config = loadConfig();
28
27
  console.log(`Generating models from: ${definitionsPath}`);
29
28
  console.log(`Output directory: ${config.paths.modelsDir}`);
30
29
  console.log(`Fields directory: ${config.paths.fieldsDir}`);
@@ -50,21 +49,10 @@ function generateModels(definitionsPath) {
50
49
  }
51
50
  }
52
51
 
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
52
  function main() {
66
- const config = loadConfig();
67
- const definitionsPath = getDefinitionsPath(config);
53
+ const definitionsPath = config.paths.modelsDefinitionPath
54
+ ? path.resolve(process.cwd(), config.paths.modelsDefinitionPath)
55
+ : path.resolve(process.cwd(), "./models.yaml");
68
56
 
69
57
  // Initial generation
70
58
  generateModels(definitionsPath);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
@@ -27,7 +27,7 @@
27
27
  "license": "MIT",
28
28
  "repository": {
29
29
  "type": "git",
30
- "url": "git+https://github.com/adriangraham/dynamo-bao.git"
30
+ "url": "https://github.com/aag1024/dynamo-bao"
31
31
  },
32
32
  "dependencies": {
33
33
  "@aws-sdk/client-dynamodb": "^3.521.0",
package/src/config.js CHANGED
@@ -3,15 +3,26 @@ const path = require("path");
3
3
  const dotenv = require("dotenv");
4
4
 
5
5
  function findConfig() {
6
+ // First check environment variable
7
+ if (process.env.DYNAMO_BAO_CONFIG) {
8
+ const configPath = path.resolve(
9
+ process.cwd(),
10
+ process.env.DYNAMO_BAO_CONFIG,
11
+ );
12
+ if (fs.existsSync(configPath)) {
13
+ const rawConfig = require(configPath);
14
+ const configDir = path.dirname(configPath);
15
+ return normalizeConfig(rawConfig, configDir);
16
+ }
17
+ }
18
+
6
19
  const possibleNames = [
7
- "config.js",
8
20
  "dynamo-bao.config.js",
9
21
  ".dynamo-bao/config.js",
22
+ "config.js",
10
23
  ];
11
24
  const searchPaths = [
12
25
  process.cwd(), // Project root
13
- // path.join(__dirname, '..'), // Library root
14
- // path.join(__dirname, '../test'), // Library test directory
15
26
  ];
16
27
 
17
28
  // Search each directory for config files
@@ -21,16 +32,7 @@ function findConfig() {
21
32
  if (fs.existsSync(configPath)) {
22
33
  const rawConfig = require(configPath);
23
34
  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
- };
35
+ return normalizeConfig(rawConfig, configDir);
34
36
  }
35
37
  }
36
38
  }
@@ -55,6 +57,24 @@ function findConfig() {
55
57
  };
56
58
  }
57
59
 
60
+ function normalizeConfig(rawConfig, configDir) {
61
+ return {
62
+ ...rawConfig,
63
+ paths: {
64
+ ...rawConfig.paths,
65
+ modelsDir: rawConfig.paths.modelsDir
66
+ ? path.resolve(configDir, rawConfig.paths.modelsDir)
67
+ : null,
68
+ modelsDefinitionPath: rawConfig.paths.modelsDefinitionPath
69
+ ? path.resolve(configDir, rawConfig.paths.modelsDefinitionPath)
70
+ : null,
71
+ fieldsDir: rawConfig.paths.fieldsDir
72
+ ? path.resolve(configDir, rawConfig.paths.fieldsDir)
73
+ : null,
74
+ },
75
+ };
76
+ }
77
+
58
78
  // Load config once at module level
59
79
  const config = findConfig();
60
80
  module.exports = config;