Skip to content

bandsintown/dynamo-node

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

46 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DynamoDB ORM

Travis-ci Code Climate

This DynamoDB ORM for node.js aims to provide a beautiful, simple and complete implementation to work with dynamodb databases. You can easily select a table and start querying/writing data, from simple requests to conditional ones without prior knowledge.

Current features:

  • Expression Abstraction : Condition, Attribute values/names
  • Conditional Requests : Add, update, delete conditionally
  • Attribute Functions : begins_with, contains, typeIs
  • Incrementing Decrementing
  • List, Set Append/Remove
  • Attribute Removal

Please note this repository is a work in progress. Contributions are welcome.

Requirements

Install package from npm or yarn

> npm install dynamo-node || yarn add dynamo-node

You can either set your AWS credentials as env variables or as a JSON file

// AWS credentials as JSON file
{
  "accessKeyId": "myKey",
  "secretAccessKey": "yourSecret",
}
# AWS credentials as ENV vars
AWS_SECRET_ACCESS_KEY="myKey"
AWS_ACCESS_KEY_ID="yourSecret"

Require module

const DynamoDB = require('dynamo-node')(region [, credit_path ]);
// e.g with json credentials
const DynamoDB = require('dynamo-node')('eu-central-1', './credits.json');
// e.g with env vars
const DynamoDB = require('dynamo-node')('eu-central-1');

Usage


Tables

Inits your table, or sets tablename for further creation

// "users" refers to the TableName we want to query from
const UserTable = DynamoDB.select('users');

Create

Attribute types association

S SS N NS B BS BOOL NULL L M
String String Set Number Number Set Binary Binary Set Boolean Null List Map
UserTable.createTable({
    KeySchema: [       
        { AttributeName: "name", KeyType: "HASH"},  //Partition key
        { AttributeName: "uid", KeyType: "RANGE" }  //Sort key
    ],
    AttributeDefinitions: [       
        { AttributeName: "uid", AttributeType: "N" },
        { AttributeName: "name", AttributeType: "S" }
    ],
    ProvisionedThroughput: {       
        ReadCapacityUnits: 10,
        WriteCapacityUnits: 10
    }
});

Delete

UserTable.deleteTable();

Items

Add

UserTable.add({
  name: "abdu", // Primary Key
  participants: ["A", "B", "C", "D"],
  last: "D"
});

Get

UserTable.get({ name: "abdu" });

Update

// if "abdu" doesn't exist, it will be added (upsert)
UserTable.update({ name: "abdu" }, {
  friends: ["abdu", "chris"],
  points: 450,
});

// nested properties, assuming clothes is set and is of type Map
UserTable.update({ name: "abel" }, {
  'clothes.shirts': 10,
  'clothes.polos': 3
});

Delete

UserTable.delete({ name: "abdu" });

Query

UserTable.query('name', '=', 'abdu');

// Using global secondary index
UserTable.useIndex('age-index').query('age', '=', 5);

Scan

Returns all items from table

UserTable.scan();

Conditional Queries

Check if attribute exists

const newUser = { name: "abel", age: 34 };

UserTable.exists('name').add(newUser);
UserTable.exists( ['name', 'age'] ).add(newUser);

UserTable.notExists('name').add(newUser);
UserTable.notExists( ['name', 'age'] ).add(newUser);

Attribute comparison

const hector = { name: "hector" };

UserTable.add({ name: "hector", last_connection: 50, age: 10, friends: { nice: 0, bad: 10 } });

// Deletes it
UserTable
  .if('last_connection', '>', 30 )
  .if('last_connection', '<', 100)
  .if('age', '<>', 90) // different than
  .delete(hector);

// Updates it
UserTable
  .if('last_connection', '=', 50)
  .if('friends.bad', '>=', 0)
  .if('age', '<=', 10)
  .update(hector, { candy: 1 });

Attribute functions

const momo = { name: "momo" };

UserTable.where('name', 'beginsWith', 'm').update(momo, { nickname: "momomo" });
UserTable.where('nickname', 'contains', 'mo').update(momo, { friends: ["lololo"] });

// Please refer to "Attribute types association" section for the list of type attributes
UserTable.where('friends', 'typeIs', 'N').update(momo, { friends: 0 }); // Won't update

Attribute manipulation

Increment/Decrement attribute

const burger = { name: 'burger' };

FoodTable.add({ name: 'burger', sold: 0, sellers: [5,8], ingredients: { cheese: 2 } });

FoodTable.increment('sold', 10).update(burger); // { sold: 10 }
FoodTable.decrement('sold', 1).update(burger); // { sold: 9 }

FoodTable.increment('ingredients.cheese', 4).update(burger);
FoodTable.decrement('ingredients.cheese', 1).update(burger);

Remove attribute

FoodTable.removeAttribute(burger, [ 'ingredients.cheese' ]);
FoodTable.removeAttribute(burger, [ 'sold', 'ingredients' ]);
// burger is now { name: burger, sellers: [5,8] }

Add to/Remove from list attribute

FoodTable.addToList({ sellers: [9] }).update(burger) // { ..., sellers: [5,8,9] }
FoodTable.removeFromList({ sellers: [8, 5] }).update(burger) // { ..., sellers: [9] }

Batch Operations

// No need to provide a table name this time
const Batch = DynamoDB.select();
const batchGet = {
    'table1': {
        // 'name' is the primary key of table1
        Keys: { 'name': ['myItem', 'myItem2', 'myItem3', 'myItem4'] }
    },
    'table2': {
        // 'pid' is the primary key of table2
        Keys: { 'pid': [1101, 1110, 1010] }
    }
};
Batch.batchGet(batchGet);
const batchPut = {
    'table1': [ { name: 'a'}, { name: 'b' }, { name: 'c' }, { name: 'd' } ],
    'table2': [ { pid: 1 }, { pid: 2 }, { pid: 3 }, { pid: 4 } ],
};

Batch.batchPut(batchPut);
const batchDelete = {
    'table1': [ { name: 'b' }, { name: 'c' } ],
    'table2': [ { pid: 3 }, { pid: 4 } ],
};

Batch.batchDelte(batchDelete);

Return values

Following previous examples, here's how you handle return values from each methods.

Note: All methods return promises

// outputs "Abdu"
UserTable.get({ name: "abdu" })
    .then(item => console.log(item.name));

// outputs "26"
UserTable.update({ name: "abdu" }, { age: "26" })
    .then(item => console.log(item.age));

// both outputs "{}"
UserTable.delete({ name: "abdu" })
    .then(item => console.log(item));

UserTable.add({ name: "Chris", age: "65" })
    .then(item => console.log(item));

Tests

Tests are located in the ./tests folder Note that you have to create two Tables named "aws.table.for.testing" and "aws.table.combined.for.testing" in order for them to run correctly.

Here's full testing process using npm scripts

> npm run createTable // can take a few seconds to be created even after process exits
> npm run test

About

most handy DynamoDB mapper yet

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%