NOTE This is a temporary fork of https://www.npmjs.com/package/dynamodb until PRs are merged
dynamodb
is a DynamoDB data mapper for node.js.
Features
- Simplified data modeling and mapping to DynamoDB types
- Advanced chainable apis for query and scan operations
- Data validation
- Autogenerating UUIDs
- Global Secondary Indexes
- Local Secondary Indexes
- Parallel Scans
Installation
npm install dynamodb
Getting Started
First, you need to configure the AWS SDK with your credentials.
var dynamo = ;dynamoAWSconfig;
When running on EC2 its recommended to leverage EC2 IAM roles. If you have configured your instance to use IAM roles, DynamoDB will automatically select these credentials for use in your application, and you do not need to manually provide credentials in any other format.
var dynamo = ;dynamoAWSconfig; // region must be set
You can also directly pass in your access key id, secret and region.
- Its recommend you not hard-code credentials inside an application. Use this method only for small personal scripts or for testing purposes.
var dynamo = ;dynamoAWSconfig;
Currently the following region codes are available in Amazon:
Code | Name |
---|---|
ap-northeast-1 | Asia Pacific (Tokyo) |
ap-southeast-1 | Asia Pacific (Singapore) |
ap-southeast-2 | Asia Pacific (Sydney) |
eu-central-1 | EU (Frankfurt) |
eu-west-1 | EU (Ireland) |
sa-east-1 | South America (Sao Paulo) |
us-east-1 | US East (N. Virginia) |
us-west-1 | US West (N. California) |
us-west-2 | US West (Oregon) |
Define a Model
Models are defined through the toplevel define method.
var Account = dynamo;
Models can also be defined with hash and range keys.
var BlogPost = dynamo;
Create Tables for all defined modules
dynamo;
When creating tables you can pass specific throughput settings for any defined models.
dynamo;
Delete Table
BlogPost;
Schema Types
DynamoDB provides the following schema types:
- String
- Number
- StringSet
- NumberSet
- Boolean
- Date
- UUID
- TimeUUID
UUID
UUIDs can be declared for any attributes, including hash and range keys. By Default, the uuid will be automatically generated when attempting to create the model in DynamoDB.
var Tweet = dynamo;
Configuration
You can configure dynamo to automatically add createdAt
and updatedAt
timestamp attributes when
saving and updating a model. updatedAt
will only be set when updating a record and will not be set on initial creation of the model.
var Account = dynamo;
If you want dynamo to handle timestamps, but only want some of them, or want your timestamps to be called something else, you can override each attribute individually:
var Account = dynamo;
You can override the table name the model will use.
var Event = dynamo;
if you set the tableName to a function, dynamo will use the result of the function as the active table to use. Useful for storing time series data.
var Event = dynamo;
After you've defined your model you can configure the table name to use. By default, the table name used will be the lowercased and pluralized version of the name you provided when defining the model.
Account;
You can also pass in a custom instance of the aws-sdk DynamoDB client
var dynamodb = ;Account; // or globally use custom DynamoDB instance// all defined models will now use this driverdynamo;
Saving Models to DynamoDB
With your models defined, we can start saving them to DynamoDB.
Account;
You can also first instantiate a model and then save it.
var acc = email: 'test@example.com' name: 'Test Example';acc;
Saving models that require range and hashkeys are identical to ones with only hashkeys.
BlogPost;
Pass an array of items and they will be saved in parallel to DynamoDB.
var item1 = email: 'foo1@example.com' name: 'Foo 1' age: 10;var item2 = email: 'foo2@example.com' name: 'Foo 2' age: 20;var item3 = email: 'foo3@example.com' name: 'Foo 3' age: 30; Account;
Use expressions api to do conditional writes
var params = {}; paramsConditionExpression = '#i <> :x'; paramsExpressionAttributeNames = '#i' : 'id'; paramsExpressionAttributeValues = ':x' : 123; User;
Use the overwrite
option to prevent over writing of existing records.
- By default
overwrite
is set to true, allowing create operations to overwrite existing records
// setting overwrite to false will generate // the same Condition Expression as in the previous example User;
Updating
When updating a model the hash and range key attributes must be given, all other attributes are optional
// update the name of the foo@example.com accountAccount;
Model.update
accepts options to pass to DynamoDB when making the updateItem request
Account; // Only update the account if the current age of the account is 21Account; // setting an attribute to null will delete the attribute from DynamoDBAccount;
You can also pass what action to perform when updating a given attribute Use $add to increment or decrement numbers and add values to sets
Account; BlogPost; BlogPost;
$del will remove values from a given set
BlogPost; BlogPost;
Use the expressions api to update nested documents
var params = {}; paramsUpdateExpression = 'SET #year = #year + :inc, #dir.titles = list_append(#dir.titles, :title), #act[0].firstName = :firstName ADD tags :tag'; paramsConditionExpression = '#year = :current'; paramsExpressionAttributeNames = '#year' : 'releaseYear' '#dir' : 'director' '#act' : 'actors' ; paramsExpressionAttributeValues = ':inc' : 1 ':current' : 2001 ':title' : 'The Man' ':firstName' : 'Rob' ':tag' : dynamo ; Movie;
Deleting
You delete items in DynamoDB using the hashkey of model If your model uses both a hash and range key, than both need to be provided
Account; // Destroy model using hash and range keyBlogPost; BlogPost;
Model.destroy
accepts options to pass to DynamoDB when making the deleteItem request
Account; Account
Use expression apis to perform conditional deletes
var params = {};paramsConditionExpression = '#v = :x';paramsExpressionAttributeNames = '#v' : 'version';paramsExpressionAttributeValues = ':x' : '2'; User;
Loading models from DynamoDB
The simpliest way to get an item from DynamoDB is by hashkey.
Account;
Perform the same get request, but this time peform a consistent read.
Account;
Model.get
accepts any options that DynamoDB getItem request supports. For
example:
Account;
Get a model using hash and range key.
// load up blog post written by Werner, titled DynamoDB Keeps Getting Better and cheaperBlogPost;
Model.get
also supports passing an object which contains hash and range key
attributes to load up a model
BlogPost;
Use expressions api to select which attributes you want returned
User;
Query
For models that use hash and range keys DynamoDB provides a flexible and chainable query api
// query for blog posts by werner@example.comBlogPost ; // same as above, but load all resultsBlogPost ; // only load the first 5 posts by wernerBlogPost ; // query for posts by werner where the tile begins with 'Expanding'BlogPost ; // return only the count of documents that begin with the title ExpandingBlogPost ; // only return title and content attributes of 10 blog posts// that begin with the title ExpandingBlogPost attributes'title' 'content' ; // sorting by title ascendingBlogPost // sorting by title descendingBlogPost // All query options are chainableBlogPost attributes'title' 'content' ;
DynamoDB supports all the possible KeyConditions that DynamoDB currently supports.
BlogPost ; // less than equalsBlogPost ; // less thanBlogPost ; // greater thanBlogPost ; // greater than equalsBlogPost ; BlogPost ; BlogPost ;
Query Filters allow you to further filter results on non-key attributes.
BlogPost ;
Expression Filters also allow you to further filter results on non-key attributes.
BlogPost ;
See the queryFilter.js example for more examples of using query filters
Global Indexes
First, define a model with a global secondary index.
var GameScore = dynamo;
Now we can query against the global index
GameScore ;
When can also configure the attributes projected into the index. By default all attributes will be projected when no Projection parameter is present
var GameScore = dynamo;
Filter items against the configured rangekey for the global index.
GameScore ;
Local Secondary Indexes
First, define a model using a local secondary index
var BlogPost = dynamo;
Now we can query for blog posts using the secondary index
BlogPost ;
Could also query for published posts, but this time return oldest first
BlogPost ;
Finally lets load all published posts sorted by publish date
BlogPost ;
Learn more about secondary indexes
Scan
DynamoDB provides a flexible and chainable api for scanning over all your items This api is very similar to the query api.
// scan all accounts, returning the first page or resultsAccount; // scan all accounts, this time loading all results// note this will potentially make several calls to DynamoDB// in order to load all resultsAccount ; // Load 20 accountsAccount ; // Load All accounts, 20 at a time per requestAccount ; // Load accounts which match a filter// only return email and created attributes// and return back the consumed capacity the request tookAccount attributes'email''created' ; // Returns number of matching accounts, rather than the matching accounts themselvesAccount ; // Start scan using start keyAccount
DynamoDB supports all the possible Scan Filters that DynamoDB currently supports.
// equalsAccount ; // not equalsAccount ; // less than equalsAccount ; // less thanAccount ; // greater than equalsAccount ; // greater thanAccount ; // name attribute doesn't existAccount ; // name attribute existsAccount ; // containsAccount ; // not containsAccount ; // inAccount ; // begins withAccount ; // betweenAccount ; // multiple filtersAccount ;
You can also use the new expressions api when filtering scans
User ;
Parallel Scan
Parallel scans increase the throughput of your table scans. The parallel scan operation is identical to the scan api. The only difference is you must provide the total number of segments
Caution you can easily consume all your provisioned throughput with this api
var totalSegments = 8; Account attributes'age' ; // Load All accountsAccount
More info on Parallel Scans
Batch Get Items
Model.getItems
allows you to load multiple models with a single request to DynamoDB.
DynamoDB limits the number of items you can get to 100 or 1MB of data for a single request. DynamoDB automatically handles splitting up into multiple requests to load all items.
Account; // For models with range keys you must pass in objects of hash and range key attributesvar postKey1 = email : 'test@example.com' title : 'Hello World!';var postKey2 = email : 'test@example.com' title : 'Another Post'; BlogPost;
Model.getItems
accepts options which will be passed to DynamoDB when making the batchGetItem request
// Get both accounts, using a consistent readAccount;
Streaming api
dynamo supports a basic streaming api in addition to the callback
api for query
, scan
, and parallelScan
operations.
var stream = Account; stream; stream; var querystream = BlogPost; querystream; querystream;
Dynamic Table Names
dynamo supports dynamic table names, useful for storing time series data.
var Event = dynamo;
Logging
Logging can be enabled to provide detailed information on data being sent and returned from DynamoDB. By default logging is turned off.
dynamolog; // enabled INFO log level
Logging can also be enabled / disabled at the model level.
var Account = dynamo;var Event = dynamo; Accountlog; // enable WARN log level for Account model operations
Examples
var dynamo = ; var Account = dynamo; Account;
See the examples for more working sample code.
Support
DynamoDB is provided as-is, free of charge. For support, you have a few choices:
- Ask your support question on Stackoverflow.com, and tag your question with dynamodb.
- If you believe you have found a bug in dynamodb, please submit a support ticket on the Github Issues page for dynamo. We'll get to them as soon as we can.
Maintainers
Authors
License
(The MIT License)
Copyright (c) 2016 Ryan Fitzgerald
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.