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.
package/README.md ADDED
@@ -0,0 +1,333 @@
1
+ # DynamoBao
2
+
3
+ DynamoBao is a simple lightweight library for building DynamoDB models in JavaScript. I've used
4
+ DynamoDB for years and generally love it, but find getting started difficult and repetitive.
5
+ DynamoBao is the tool I wish I had when I started.
6
+
7
+ ## Principles
8
+
9
+ - Expose just enough of Dynamo's features to make it easy to model many common types of data.
10
+ - Don't break DynamoDB's superpower of infinite scale with consistent fast performance.
11
+ - Use single table design to minimize ops overhead, without adding complexity for the developer.
12
+
13
+ ## Key features
14
+
15
+ - Model 1:1, 1:N, N:M relationships between objects
16
+ - Efficiently load data: load related objects in parallel, cache data using a loading context
17
+ - Minimize race conditions: save diffs, optimistic locking, version checks, atomic counters
18
+ - Enforce unique constraints and use them for lookups
19
+ - Return total read/write consumed capacity (even when multiple operations were performed)
20
+
21
+ ## Example 1: Simple model
22
+
23
+ Step 1 is to define your models in a yaml file. Here's a simple example.
24
+
25
+ ```
26
+ models:
27
+ User: {
28
+ modelPrefix: u,
29
+ fields: {
30
+ userId: {type: UlidField, autoAssign: true, required: true},
31
+ name: {type: StringField, required: true},
32
+ email: {type: EmailField, required: true}
33
+ },
34
+ primaryKey: {partitionKey: userId}
35
+ }
36
+ ```
37
+
38
+ Based on this definition, the code generator will create a `User` model (in models/user) that you can use like this:
39
+
40
+ ```
41
+ const { User } = require("./models/user");
42
+ const userConfig = require("./config");
43
+ const dynamoBao = require("dynamo-bao");
44
+ async function testUserModel() {
45
+ try {
46
+ dynamoBao.initModels(userConfig);
47
+
48
+ // Create a new user
49
+ const user = new User({
50
+ name: "Test User",
51
+ email: "test@example.com",
52
+ });
53
+
54
+ await user.save();
55
+ console.log("Created user:", user);
56
+ console.log("Consumed capacity:", user.getNumericConsumedCapacity());
57
+ }
58
+ }
59
+
60
+ testUserModel();
61
+ ```
62
+
63
+ ## Example 2: Relationships and unique constraints
64
+
65
+ ```
66
+ models:
67
+ User: {
68
+ modelPrefix: u,
69
+ fields: {
70
+ userId: {type: UlidField, autoAssign: true, required: true},
71
+ name: {type: StringField, required: true},
72
+ email: {type: EmailField, required: true}
73
+ },
74
+ primaryKey: {partitionKey: userId},
75
+ uniqueConstraints: {uniqueEmail: {field: email, uniqueConstraintId: uc1}}
76
+ }
77
+ Post: {
78
+ modelPrefix: p,
79
+ fields: {
80
+ postId: {type: UlidField, autoAssign: true},
81
+ userId: {type: RelatedField, model: User, required: true},
82
+ title: {type: StringField, required: true},
83
+ content: {type: StringField, required: true}
84
+ },
85
+ primaryKey: {partitionKey: postId},
86
+ indexes: {postsForUser: {partitionKey: userId, sortKey: postId, indexId: gsi2}}
87
+ }
88
+ ```
89
+
90
+ ```
91
+ const { User } = require("./models/user");
92
+ const { Post } = require("./models/post");
93
+ const userConfig = require("./config");
94
+ const dynamoBao = require("dynamo-bao");
95
+ async function testUserModel() {
96
+ try {
97
+ dynamoBao.initModels(userConfig);
98
+
99
+ // Create a new user
100
+ const user = new User({
101
+ name: "Test User",
102
+ email: "test@example.com",
103
+ });
104
+
105
+ await user.save();
106
+ console.log("Created user:", user.userId);
107
+
108
+ // Find user by unique constraint
109
+ const foundUser = await User.findByEmail("test@example.com");
110
+ console.log("Found user by email:", foundUser);
111
+
112
+
113
+ // Create some test posts for the user
114
+ const post1 = new Post({
115
+ userId: user.userId,
116
+ title: "Test Post 1",
117
+ content: "This is a test post",
118
+ });
119
+
120
+ const post2 = new Post({
121
+ userId: user.userId,
122
+ title: "Test Post 2",
123
+ content: "This is another test post",
124
+ });
125
+
126
+ await Promise.all([post1.save(), post2.save()]);
127
+
128
+ // User now has a queryPosts method (via the postsForUser index)
129
+ const userPosts = await user.queryPosts();
130
+ console.log("User posts:", userPosts.items.length);
131
+
132
+ // Or add a filter condition to the query
133
+ const filteredPosts = await user.queryPosts(null, {
134
+ filter: {
135
+ content: {
136
+ $contains: "another"
137
+ }
138
+ }
139
+ });
140
+ console.log("User posts matching filter:", filteredPosts.items.length);
141
+
142
+ }
143
+ }
144
+
145
+ testUserModel();
146
+ ```
147
+
148
+ ## Installation / Quick Start
149
+
150
+ Make sure you have [AWS credentials setup in your environment](https://medium.com/@simonazhangzy/installing-and-configuring-the-aws-cli-7d33796e4a7c). You'll also need [node and npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) installed.
151
+
152
+ Install DynamoBao globally:
153
+
154
+ ```
155
+ npm install -g dynamo-bao
156
+ ```
157
+
158
+ Create a new Dynamo table for your project. You should have one table per project.
159
+
160
+ ```
161
+ bao-create-table
162
+ ```
163
+
164
+ Create a project and setup some models.
165
+
166
+ ```
167
+ mkdir your-project
168
+ cd your-project
169
+ ```
170
+
171
+ Create a simple `config.js` file:
172
+
173
+ ```
174
+ const path = require("path");
175
+
176
+ const config = {
177
+ aws: {
178
+ region: "us-west-2",
179
+ },
180
+ db: {
181
+ tableName: "dynamo-bao-dev", // make sure this matches what you created with bao-create-table
182
+ },
183
+ logging: {
184
+ level: "ERROR",
185
+ },
186
+ paths: {
187
+ modelsDir: path.resolve(__dirname, "./models"),
188
+ modelsDefinitionPath: path.resolve(__dirname, "./models.yaml"),
189
+ fieldsDir: path.resolve(__dirname, "./fields"), // optional for custom fields
190
+ },
191
+ };
192
+
193
+ module.exports = config;
194
+ ```
195
+
196
+ Edit your `models.yaml` file to define your models.
197
+
198
+ ```
199
+ models:
200
+ User:
201
+ modelPrefix: u
202
+ fields: {
203
+ userId: {type: UlidField, autoAssign: true, required: true},
204
+ name: {type: StringField, required: true},
205
+ email: {type: StringField, required: true},
206
+ profilePictureUrl: {type: StringField},
207
+ createdAt: {type: CreateDateField},
208
+ modifiedAt: {type: ModifiedDateField},
209
+ role: {type: StringField}
210
+ },
211
+ primaryKey: {partitionKey: userId},
212
+ uniqueConstraints: {
213
+ uniqueEmail: {field: email, uniqueConstraintId: uc1}
214
+ }
215
+ Post:
216
+ modelPrefix: p
217
+ fields: {
218
+ postId: {type: UlidField, autoAssign: true},
219
+ userId: {type: RelatedField, model: User, required: true},
220
+ title: {type: StringField, required: true},
221
+ content: {type: StringField, required: true},
222
+ createdAt: {type: CreateDateField},
223
+ version: {type: VersionField}
224
+ },
225
+ primaryKey: {partitionKey: postId},
226
+ indexes: {
227
+ allPosts: {partitionKey: modelPrefix, sortKey: postId, indexId: gsi1},
228
+ postsForUser: {partitionKey: userId, sortKey: createdAt, indexId: gsi2}
229
+ }
230
+ ```
231
+
232
+ Run the code generator to create the models. You can also run `bao-watch` to automatically regenerate the models when you make changes.
233
+
234
+ ```
235
+ bao-codegen
236
+ ```
237
+
238
+ You should now have a `models` directory with the generated models.
239
+
240
+ Let's try using the models. Add the following code to a file called `example.js`.
241
+
242
+ ```
243
+ # example.js
244
+ const { User } = require("./models/user");
245
+ const { Post } = require("./models/post");
246
+ const userConfig = require("./config");
247
+ const dynamoBao = require("dynamo-bao");
248
+ async function testUserModel() {
249
+ try {
250
+ dynamoBao.initModels(userConfig);
251
+
252
+ // Find user by email
253
+ const existingUser = await User.findByEmail("test@example.com");
254
+ console.log("Found user by email:", existingUser.getPrimaryId());
255
+ if (existingUser.exists()) {
256
+ await User.delete(existingUser.getPrimaryId());
257
+ console.log("Deleted existing user");
258
+ await new Promise((resolve) => setTimeout(resolve, 100)); // 100ms
259
+ }
260
+
261
+ // Create a new user
262
+ const user = new User({
263
+ name: "Test User",
264
+ email: "test@example.com",
265
+ role: "user",
266
+ profilePictureUrl: "https://example.com/profile.jpg",
267
+ });
268
+
269
+ await user.save();
270
+ console.log("Created user:", user.getPrimaryId());
271
+
272
+ // Find user by email
273
+ const foundUser = await User.findByEmail("test@example.com");
274
+ console.log("Found user by email:", foundUser.getPrimaryId());
275
+
276
+ // Create some test posts for the user
277
+ const post1 = new Post({
278
+ userId: user.userId,
279
+ title: "Test Post 1",
280
+ content: "This is a test post",
281
+ });
282
+
283
+ const post2 = new Post({
284
+ userId: user.userId,
285
+ title: "Test Post 2",
286
+ content: "This is another test post",
287
+ });
288
+
289
+ await Promise.all([post1.save(), post2.save()]);
290
+
291
+ // Query user posts
292
+ const userPosts = await user.queryPosts();
293
+ console.log("User posts:", userPosts.items.length);
294
+
295
+ // Or add a filter condition to the query
296
+ const filteredPosts = await user.queryPosts(null, {
297
+ filter: { content: { $contains: "another" } },
298
+ });
299
+ console.log("User posts matching filter:", filteredPosts.items.length);
300
+ } catch (error) {
301
+ console.error("Error:", error);
302
+ }
303
+ }
304
+
305
+ // Run the test
306
+ testUserModel();
307
+ ```
308
+
309
+ Run the example.
310
+
311
+ ```
312
+ node example.js
313
+ ```
314
+
315
+ You should see something similar to this:
316
+
317
+ ```
318
+ % node example.js
319
+ Found user by email: false
320
+ Created user: 01JFGMRH7XACZ8GKB81DZ5YWNH
321
+ Found user by email: 01JFGMRH7XACZ8GKB81DZ5YWNH
322
+ User posts: 2
323
+ User posts matching filter: 1
324
+ ```
325
+
326
+ Congratulations! You're now harnessing the power of DynamoDB.
327
+
328
+ It's worth noting that you didn't have to:
329
+
330
+ - Configure or create a new table when adding a new model
331
+ - Install a database (either locally or on a server)
332
+ - Understand how to generate keys and indexes using single table design princples
333
+ - Manually configure transactions and items to support unique constraints
@@ -0,0 +1,60 @@
1
+ const path = require("path");
2
+ const fs = require("fs").promises;
3
+ const os = require("os");
4
+ const chokidar = require("chokidar");
5
+
6
+ async function testChokidar() {
7
+ let tempDir = path.join(os.tmpdir(), "chokidar-test-" + Date.now());
8
+ await fs.mkdir(tempDir, { recursive: true });
9
+
10
+ const testFile = path.join(tempDir, "test-file.js");
11
+ await fs.writeFile(testFile, "// Initial content");
12
+
13
+ console.log("Watching directory:", tempDir);
14
+ console.log("Test file path:", testFile);
15
+
16
+ // DON'T DO THIS tempDir = path.join(tempDir, '**/*.js');
17
+
18
+ const watcher = chokidar.watch(tempDir, {
19
+ // Changed to watch entire directory
20
+ persistent: true,
21
+ ignoreInitial: false, // Changed to false to see initial add events
22
+ usePolling: true,
23
+ interval: 100,
24
+ awaitWriteFinish: {
25
+ stabilityThreshold: 100,
26
+ pollInterval: 100,
27
+ },
28
+ });
29
+
30
+ watcher
31
+ .on("add", (path) => console.log(`File ${path} has been added`))
32
+ .on("change", (filepath) => {
33
+ console.log("Change detected:", filepath);
34
+ })
35
+ .on("error", (error) => console.log(`Watcher error: ${error}`))
36
+ .on("ready", () => {
37
+ console.log("Watcher is ready");
38
+
39
+ setTimeout(async () => {
40
+ console.log("Modifying file");
41
+ try {
42
+ await fs.writeFile(testFile, "// Modified content");
43
+ console.log("File modification completed");
44
+ } catch (err) {
45
+ console.error("Error modifying file:", err);
46
+ }
47
+ }, 1000);
48
+ });
49
+
50
+ // Keep process alive longer
51
+ setTimeout(() => {
52
+ console.log("Closing watcher");
53
+ watcher.close();
54
+ }, 10000); // Increased timeout to 10 seconds
55
+ }
56
+
57
+ testChokidar().catch((err) => {
58
+ console.error("Test failed:", err);
59
+ process.exit(1);
60
+ });
package/bin/codegen.js ADDED
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const yaml = require("js-yaml");
6
+ const { generateModelFiles } = require("./generators/model");
7
+ const { createLogger } = require("./utils/scriptLogger");
8
+ const FieldResolver = require("../src/fieldResolver");
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
+ }
28
+
29
+ function loadModelDefinitions(definitionsPath, fieldResolver) {
30
+ const models = {};
31
+
32
+ if (fs.statSync(definitionsPath).isDirectory()) {
33
+ // Load all .yaml files from directory
34
+ const files = fs
35
+ .readdirSync(definitionsPath)
36
+ .filter((file) => file.endsWith(".yaml") || file.endsWith(".yml"));
37
+
38
+ logger.debug("Found YAML files:", files);
39
+
40
+ files.forEach((file) => {
41
+ const filePath = path.join(definitionsPath, file);
42
+ logger.debug(`Loading file: ${filePath}`);
43
+
44
+ const fileContents = fs.readFileSync(filePath, "utf8");
45
+ const definition = yaml.load(fileContents);
46
+
47
+ logger.debug(`Loaded definition from ${file}:`, definition);
48
+
49
+ // Merge models from this file
50
+ if (definition && definition.models) {
51
+ Object.assign(models, definition.models);
52
+ } else {
53
+ console.warn(`Warning: No models found in ${file}`);
54
+ }
55
+ });
56
+ } else {
57
+ // Load single file
58
+ const fileContents = fs.readFileSync(definitionsPath, "utf8");
59
+ const definition = yaml.load(fileContents);
60
+ if (definition && definition.models) {
61
+ Object.assign(models, definition.models);
62
+ }
63
+ }
64
+
65
+ logger.debug("Final merged models:", models);
66
+ return { models, fieldResolver };
67
+ }
68
+
69
+ function main() {
70
+ const args = process.argv.slice(2);
71
+
72
+ // Set default paths
73
+ let definitionsPath = path.resolve(process.cwd(), "./models.yaml");
74
+ let outputDir = path.resolve(process.cwd(), "./models");
75
+
76
+ // Override with command line arguments if provided
77
+ if (args.length >= 1) {
78
+ definitionsPath = path.resolve(process.cwd(), args[0]);
79
+ }
80
+ if (args.length >= 2) {
81
+ outputDir = path.resolve(process.cwd(), args[1]);
82
+ }
83
+
84
+ console.log("codegen definitionsPath", definitionsPath);
85
+ try {
86
+ const config = loadConfig(definitionsPath);
87
+ console.log("codegen config", config);
88
+
89
+ // Built-in fields are in fields.js
90
+ const builtInFieldsPath = path.resolve(__dirname, "../src/fields.js");
91
+
92
+ const fieldResolver = new FieldResolver(
93
+ builtInFieldsPath,
94
+ config?.paths?.fieldsDir,
95
+ );
96
+
97
+ const definitions = loadModelDefinitions(definitionsPath, fieldResolver);
98
+ generateModelFiles(
99
+ definitions.models,
100
+ outputDir,
101
+ definitions.fieldResolver,
102
+ );
103
+ } catch (error) {
104
+ console.error("Error generating models:", error);
105
+ console.error("Stack trace:", error.stack);
106
+ process.exit(1);
107
+ }
108
+ }
109
+
110
+ if (require.main === module) {
111
+ main();
112
+ }
113
+
114
+ module.exports = { loadModelDefinitions };
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env node
2
+
3
+ const {
4
+ DynamoDBClient,
5
+ CreateTableCommand,
6
+ ListTablesCommand,
7
+ } = require("@aws-sdk/client-dynamodb");
8
+ const readline = require("readline");
9
+
10
+ // Create DynamoDB client at the top level
11
+ const client = new DynamoDBClient();
12
+
13
+ async function checkAwsCredentials() {
14
+ try {
15
+ // Make a simple request that requires authentication
16
+ await client.send(new ListTablesCommand({}));
17
+ console.log("AWS credentials found and valid");
18
+ return true;
19
+ } catch (error) {
20
+ if (
21
+ error.name === "UnrecognizedClientException" ||
22
+ error.name === "AccessDeniedException" ||
23
+ error.name === "CredentialsNotFound"
24
+ ) {
25
+ console.error(
26
+ "AWS credentials not found or invalid. Please run aws configure to set your credentials.",
27
+ error.message,
28
+ );
29
+ return false;
30
+ }
31
+ // If it's a different error (like network issues), throw it
32
+ throw error;
33
+ }
34
+ }
35
+
36
+ // Function to prompt user for input
37
+ const prompt = (query) => {
38
+ const rl = readline.createInterface({
39
+ input: process.stdin,
40
+ output: process.stdout,
41
+ });
42
+
43
+ return new Promise((resolve) =>
44
+ rl.question(query, (answer) => {
45
+ rl.close();
46
+ resolve(answer);
47
+ }),
48
+ );
49
+ };
50
+
51
+ async function createTable() {
52
+ // Prompt user for table name
53
+ const defaultTableName = "dynamo-bao-dev";
54
+ const tableName =
55
+ (await prompt(`Enter table name [${defaultTableName}]: `)) ||
56
+ defaultTableName;
57
+
58
+ // Define table parameters
59
+ const params = {
60
+ TableName: tableName,
61
+ BillingMode: "PAY_PER_REQUEST",
62
+ AttributeDefinitions: [
63
+ { AttributeName: "_pk", AttributeType: "S" },
64
+ { AttributeName: "_sk", AttributeType: "S" },
65
+ { AttributeName: "_gsi1_pk", AttributeType: "S" },
66
+ { AttributeName: "_gsi1_sk", AttributeType: "S" },
67
+ { AttributeName: "_gsi2_pk", AttributeType: "S" },
68
+ { AttributeName: "_gsi2_sk", AttributeType: "S" },
69
+ { AttributeName: "_gsi3_pk", AttributeType: "S" },
70
+ { AttributeName: "_gsi3_sk", AttributeType: "S" },
71
+ { AttributeName: "_gsi_test_id", AttributeType: "S" },
72
+ ],
73
+ KeySchema: [
74
+ { AttributeName: "_pk", KeyType: "HASH" },
75
+ { AttributeName: "_sk", KeyType: "RANGE" },
76
+ ],
77
+ GlobalSecondaryIndexes: [
78
+ {
79
+ IndexName: "gsi1",
80
+ KeySchema: [
81
+ { AttributeName: "_gsi1_pk", KeyType: "HASH" },
82
+ { AttributeName: "_gsi1_sk", KeyType: "RANGE" },
83
+ ],
84
+ Projection: { ProjectionType: "ALL" },
85
+ },
86
+ {
87
+ IndexName: "gsi2",
88
+ KeySchema: [
89
+ { AttributeName: "_gsi2_pk", KeyType: "HASH" },
90
+ { AttributeName: "_gsi2_sk", KeyType: "RANGE" },
91
+ ],
92
+ Projection: { ProjectionType: "ALL" },
93
+ },
94
+ {
95
+ IndexName: "gsi3",
96
+ KeySchema: [
97
+ { AttributeName: "_gsi3_pk", KeyType: "HASH" },
98
+ { AttributeName: "_gsi3_sk", KeyType: "RANGE" },
99
+ ],
100
+ Projection: { ProjectionType: "ALL" },
101
+ },
102
+ {
103
+ IndexName: "gsi_test",
104
+ KeySchema: [{ AttributeName: "_gsi_test_id", KeyType: "HASH" }],
105
+ Projection: { ProjectionType: "ALL" },
106
+ },
107
+ ],
108
+ TimeToLiveSpecification: {
109
+ AttributeName: "ttl",
110
+ Enabled: true,
111
+ },
112
+ };
113
+
114
+ try {
115
+ // Create table
116
+ const command = new CreateTableCommand(params);
117
+ const response = await client.send(command);
118
+ console.log(
119
+ "Table created successfully:",
120
+ response.TableDescription.TableName,
121
+ );
122
+ } catch (error) {
123
+ console.error("Error creating table:", error);
124
+ }
125
+ }
126
+
127
+ async function main() {
128
+ await checkAwsCredentials();
129
+ await createTable();
130
+ }
131
+
132
+ // Run the main function
133
+ main().catch((error) => {
134
+ console.error("Error:", error);
135
+ process.exit(1);
136
+ });
File without changes