dynamo-bao 0.1.0 → 0.1.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.
package/README.md CHANGED
@@ -13,8 +13,8 @@ DynamoBao is the tool I wish I had when I started.
13
13
  ## Key features
14
14
 
15
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
16
+ - Efficiently load data: load related objects in parallel, cache data using loading contexts
17
+ - Minimize race conditions: save diffs, version checks on save, atomic counters
18
18
  - Enforce unique constraints and use them for lookups
19
19
  - Return total read/write consumed capacity (even when multiple operations were performed)
20
20
 
@@ -25,36 +25,33 @@ Step 1 is to define your models in a yaml file. Here's a simple example.
25
25
  ```
26
26
  models:
27
27
  User: {
28
- modelPrefix: u,
29
- fields: {
30
- userId: {type: UlidField, autoAssign: true, required: true},
31
- name: {type: StringField, required: true},
28
+ modelPrefix: u
29
+ fields:
30
+ userId: {type: UlidField, autoAssign: true, required: true}
31
+ name: {type: StringField, required: true}
32
32
  email: {type: EmailField, required: true}
33
- },
34
33
  primaryKey: {partitionKey: userId}
35
34
  }
36
35
  ```
37
36
 
38
- Based on this definition, the code generator will create a `User` model (in models/user) that you can use like this:
37
+ Based on this definition, the code generator will create a `User` model in the models directory that you can use like this:
39
38
 
40
39
  ```
41
40
  const { User } = require("./models/user");
42
41
  const userConfig = require("./config");
43
42
  const dynamoBao = require("dynamo-bao");
44
43
  async function testUserModel() {
45
- try {
46
- dynamoBao.initModels(userConfig);
44
+ dynamoBao.initModels(userConfig);
47
45
 
48
- // Create a new user
49
- const user = new User({
50
- name: "Test User",
51
- email: "test@example.com",
52
- });
46
+ // Create a new user
47
+ const user = new User({
48
+ name: "Test User",
49
+ email: "test@example.com",
50
+ });
53
51
 
54
- await user.save();
55
- console.log("Created user:", user);
56
- console.log("Consumed capacity:", user.getNumericConsumedCapacity());
57
- }
52
+ await user.save();
53
+ console.log("Created user:", user);
54
+ console.log("Consumed capacity:", user.getNumericConsumedCapacity());
58
55
  }
59
56
 
60
57
  testUserModel();
@@ -64,27 +61,28 @@ testUserModel();
64
61
 
65
62
  ```
66
63
  models:
67
- User: {
68
- modelPrefix: u,
69
- fields: {
70
- userId: {type: UlidField, autoAssign: true, required: true},
71
- name: {type: StringField, required: true},
64
+ User:
65
+ modelPrefix: u # required short string to identify the model
66
+ fields:
67
+ userId: {type: UlidField, autoAssign: true, required: true}
68
+ name: {type: StringField, required: true}
72
69
  email: {type: EmailField, required: true}
73
- },
74
- primaryKey: {partitionKey: userId},
70
+ primaryKey: {partitionKey: userId} # required
71
+ # Add up to 3 unique constraints each with a unique id: uc1, uc2, uc3
75
72
  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},
73
+ Post:
74
+ modelPrefix: p
75
+ fields:
76
+ postId: {type: UlidField, autoAssign: true}
77
+ # Enables getUser on a Post object / load related data
78
+ userId: {type: RelatedField, model: User, required: true}
79
+ title: {type: StringField, required: true}
83
80
  content: {type: StringField, required: true}
84
- },
85
- primaryKey: {partitionKey: postId},
86
- indexes: {postsForUser: {partitionKey: userId, sortKey: postId, indexId: gsi2}}
87
- }
81
+ primaryKey: {partitionKey: postId}
82
+ indexes:
83
+ # Add up to 3 indexes; make sure each index has a unique id: gsi1, gsi2, gsi3
84
+ # Enables user.queryPosts() to query posts for a user
85
+ postsForUser: {partitionKey: userId, sortKey: postId, indexId: gsi2}
88
86
  ```
89
87
 
90
88
  ```
@@ -93,53 +91,50 @@ const { Post } = require("./models/post");
93
91
  const userConfig = require("./config");
94
92
  const dynamoBao = require("dynamo-bao");
95
93
  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
- }
94
+ dynamoBao.initModels(userConfig);
95
+
96
+ // Create a new user
97
+ const user = new User({
98
+ name: "Test User",
99
+ email: "test@example.com",
100
+ });
101
+
102
+ await user.save();
103
+ console.log("Created user:", user.userId);
104
+
105
+ // Find user by unique constraint
106
+ const foundUser = await User.findByEmail("test@example.com");
107
+ console.log("Found user by email:", foundUser);
108
+
109
+
110
+ // Create some test posts for the user
111
+ const post1 = new Post({
112
+ userId: user.userId,
113
+ title: "Test Post 1",
114
+ content: "This is a test post",
115
+ });
116
+
117
+ const post2 = new Post({
118
+ userId: user.userId,
119
+ title: "Test Post 2",
120
+ content: "This is another test post",
121
+ });
122
+
123
+ await Promise.all([post1.save(), post2.save()]);
124
+
125
+ // User now has a queryPosts method (via the postsForUser index)
126
+ const userPosts = await user.queryPosts();
127
+ console.log("User posts:", userPosts.items.length);
128
+
129
+ // Or add a filter condition to the query
130
+ const filteredPosts = await user.queryPosts(null, {
131
+ filter: {
132
+ content: {
133
+ $contains: "another"
138
134
  }
139
- });
140
- console.log("User posts matching filter:", filteredPosts.items.length);
141
-
142
- }
135
+ }
136
+ });
137
+ console.log("User posts matching filter:", filteredPosts.items.length);
143
138
  }
144
139
 
145
140
  testUserModel();
@@ -149,98 +144,75 @@ testUserModel();
149
144
 
150
145
  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
146
 
152
- Install DynamoBao globally:
147
+ Create a project and setup some models. You'll also need to install DynamoBao locally in your project.
153
148
 
154
149
  ```
155
- npm install -g dynamo-bao
150
+ mkdir your-project
151
+ cd your-project
152
+ npm install dynamo-bao
156
153
  ```
157
154
 
158
155
  Create a new Dynamo table for your project. You should have one table per project.
159
156
 
160
157
  ```
161
- bao-create-table
158
+ npx bao-create-table
162
159
  ```
163
160
 
164
- Create a project and setup some models.
161
+ This creates a `config.js` which contains settings for your project like AWS region and the table name.
165
162
 
166
- ```
167
- mkdir your-project
168
- cd your-project
169
- ```
163
+ It also creates a `models.yaml` file with a simple example model, and a `models` directory where
164
+ the generated models will be stored.
170
165
 
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.
166
+ Edit your `models.yaml` file to define these models.
197
167
 
198
168
  ```
199
169
  models:
200
170
  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
- }
171
+ modelPrefix: u # required short string to identify the model
172
+ fields:
173
+ userId: { type: UlidField, autoAssign: true, required: true }
174
+ name: { type: StringField, required: true }
175
+ email: { type: StringField, required: true }
176
+ profilePictureUrl: { type: StringField }
177
+ createdAt: { type: CreateDateField }
178
+ modifiedAt: { type: ModifiedDateField }
179
+ role: { type: StringField }
180
+ primaryKey:
181
+ partitionKey: userId
182
+ uniqueConstraints:
183
+ # Enforces unique constraint on email field and enables User.findByEmail()
184
+ uniqueEmail: { field: email, uniqueConstraintId: uc1 }
185
+
215
186
  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
- }
187
+ modelPrefix: p # required short string to identify the model
188
+ fields:
189
+ postId: { type: UlidField, autoAssign: true }
190
+ userId: { type: RelatedField, model: User, required: true }
191
+ title: { type: StringField, required: true }
192
+ content: { type: StringField, required: true }
193
+ createdAt: { type: CreateDateField }
194
+ version: { type: VersionField }
195
+ primaryKey:
196
+ partitionKey: postId
197
+ indexes:
198
+ # Enables Post.queryAllPosts() to query all posts
199
+ allPosts: { partitionKey: modelPrefix, sortKey: postId, indexId: gsi1 }
200
+ # Enables user.queryPosts() to query posts for a user
201
+ postsForUser: { partitionKey: userId, sortKey: createdAt, indexId: gsi2 }
230
202
  ```
231
203
 
232
- Run the code generator to create the models. You can also run `bao-watch` to automatically regenerate the models when you make changes.
204
+ Run the code generator to create the models. You can also run `npx bao-watch` to automatically regenerate the models when you make changes.
233
205
 
234
206
  ```
235
- bao-codegen
207
+ npx bao-codegen
236
208
  ```
237
209
 
238
- You should now have a `models` directory with the generated models.
210
+ You should now have generated models in the `models` directory.
239
211
 
240
212
  Let's try using the models. Add the following code to a file called `example.js`.
241
213
 
242
214
  ```
243
- # example.js
215
+ // example.js
244
216
  const { User } = require("./models/user");
245
217
  const { Post } = require("./models/post");
246
218
  const userConfig = require("./config");
@@ -251,7 +223,7 @@ async function testUserModel() {
251
223
 
252
224
  // Find user by email
253
225
  const existingUser = await User.findByEmail("test@example.com");
254
- console.log("Found user by email:", existingUser.getPrimaryId());
226
+ console.log("Found user by email:", existingUser.exists());
255
227
  if (existingUser.exists()) {
256
228
  await User.delete(existingUser.getPrimaryId());
257
229
  console.log("Deleted existing user");
@@ -6,6 +6,8 @@ const {
6
6
  ListTablesCommand,
7
7
  } = require("@aws-sdk/client-dynamodb");
8
8
  const readline = require("readline");
9
+ const fs = require("fs");
10
+ const path = require("path");
9
11
 
10
12
  // Create DynamoDB client at the top level
11
13
  const client = new DynamoDBClient();
@@ -48,6 +50,39 @@ const prompt = (query) => {
48
50
  );
49
51
  };
50
52
 
53
+ async function writeConfigFile(tableName) {
54
+ const region = await client.config.region();
55
+ const configContent = `const path = require("path");
56
+
57
+ const config = {
58
+ aws: {
59
+ region: "${region}",
60
+ },
61
+ db: {
62
+ tableName: "${tableName}",
63
+ },
64
+ logging: {
65
+ level: "ERROR",
66
+ },
67
+ paths: {
68
+ // Default paths:
69
+ // models/ => generated models
70
+ // models.yaml => model definitions
71
+ // fields/ => custom fields
72
+ modelsDir: path.resolve(__dirname, "./models"),
73
+ modelsDefinitionPath: path.resolve(__dirname, "./models.yaml"),
74
+ fieldsDir: path.resolve(__dirname, "./fields"), // optional for custom fields
75
+ },
76
+ };
77
+
78
+ module.exports = config;
79
+ `;
80
+
81
+ const configPath = path.resolve(process.cwd(), "config.js");
82
+ fs.writeFileSync(configPath, configContent);
83
+ console.log(`Config file written to: ${configPath}`);
84
+ }
85
+
51
86
  async function createTable() {
52
87
  // Prompt user for table name
53
88
  const defaultTableName = "dynamo-bao-dev";
@@ -119,14 +154,50 @@ async function createTable() {
119
154
  "Table created successfully:",
120
155
  response.TableDescription.TableName,
121
156
  );
157
+
158
+ // Add this line to write the config file after table creation
159
+ await writeConfigFile(tableName);
122
160
  } catch (error) {
123
161
  console.error("Error creating table:", error);
124
162
  }
125
163
  }
126
164
 
165
+ async function createDirectoriesAndFiles() {
166
+ // Create models directory
167
+ const modelsDir = path.resolve(process.cwd(), "models");
168
+ if (!fs.existsSync(modelsDir)) {
169
+ fs.mkdirSync(modelsDir);
170
+ console.log(`Created models directory at: ${modelsDir}`);
171
+ }
172
+
173
+ // Create models.yaml with default content
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/
176
+ #
177
+ # Here's a simple example:
178
+ # models:
179
+ # User: {
180
+ #
181
+ # modelPrefix: u
182
+ # fields:
183
+ # userId: {type: UlidField, autoAssign: true, required: true}
184
+ # name: {type: StringField, required: true}
185
+ # email: {type: EmailField, required: true}
186
+ # primaryKey: {partitionKey: userId}
187
+ # }
188
+ `;
189
+
190
+ if (!fs.existsSync(modelsYamlPath)) {
191
+ fs.writeFileSync(modelsYamlPath, yamlContent);
192
+ console.log(`Created models.yaml at: ${modelsYamlPath}`);
193
+ }
194
+ }
195
+
127
196
  async function main() {
128
197
  await checkAwsCredentials();
129
198
  await createTable();
199
+ // Add this line after table creation
200
+ await createDirectoriesAndFiles();
130
201
  }
131
202
 
132
203
  // Run the main function
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+
3
+ console.log(`
4
+ 🧨🧨🧨
5
+ Are you sure you want to PERMANENTLY delete this table?
6
+
7
+ This will delete all the data in the table and cannot be undone.
8
+
9
+ If you want to do this, please use the following AWS cli command:
10
+
11
+ aws dynamodb delete-table --table-name {YOUR_TABLE_NAME}
12
+
13
+ If you don't know your table's name, look in config.js.
14
+ 🧨🧨🧨
15
+ `);
16
+
17
+ process.exit(1);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.1.0",
4
- "description": "Simple powerful data modeleling primatives for DynamoDB in JavaScript",
3
+ "version": "0.1.2",
4
+ "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
7
7
  "test": "LOG_LEVEL=OFF jest",
@@ -32,6 +32,7 @@
32
32
  "dependencies": {
33
33
  "@aws-sdk/client-dynamodb": "^3.521.0",
34
34
  "@aws-sdk/lib-dynamodb": "^3.521.0",
35
+ "chokidar": "^4.0.3",
35
36
  "dotenv": "^16.4.7",
36
37
  "js-yaml": "^4.1.0",
37
38
  "ulid": "^2.3.0"
@@ -47,8 +48,9 @@
47
48
  "serverless": "^3.38.0"
48
49
  },
49
50
  "bin": {
50
- "bao-create-table": "bin/dynamo-bao-create-table.js",
51
+ "bao-init": "bin/dynamo-bao-create-table.js",
51
52
  "bao-codegen": "bin/codegen.js",
52
- "bao-watch": "bin/watch.js"
53
+ "bao-watch": "bin/watch.js",
54
+ "bao-delete": "bin/dynamo-bao-delete-table.js"
53
55
  }
54
56
  }