DynamORM is an object-relational mapper (ORM) for interacting with DynamoDB written in Typescript.
Requires tsconfig target set to ESNext
An entity defines all attributes associated with a single DynamoDB table.
entities.ts
import {Entity, attribute} from "dynamorm";
export class AuthorEntity extends Entity {
@attribute()
private firstName;
@attribute()
private lastName;
@attribute()
private email;
@attribute()
private image;
@attribute()
private about;
@attribute()
private socialMediaLinks;
}
The @attribute
decorator accepts two parameters
- type: AttributeType - default AttributeType.String
- required: boolean - default false
import {AttributeType, attribute} from "dynamorm";
import {AttributeRequired} from "./types";
...
@attribute(AttributeType.Number, AttributeRequired)
private age;
...
This table uses email
as the partition key with no sort key.
tables.ts
import {Table, table} from "dynamorm";
@table({
name: 'Authors',
primaryKey: {pk: 'email'},
entities: [AuthorEntity]
})
export class AuthorTable extends Table {}
DynamORM wraps your database code in an object that exposes an easy to use api. This is the entry point for interacting with DynamoDB service.
db.ts
import {Dynamorm, dynamorm} from "dynamorm"
dynamorm({
client: new DynamoDBClient(),
tables: [AuthorTable]
})
class Db {}
const db = Dynamorm.create(Db)
export default db
Entities are automatically converted to
index.ts
import db from './db'
const model = db.model('AuthorEntity');
model.set('fistName', 'Jack')
model.set('lastName', 'black')
model.set('email', '[email protected]')
model.save()
.catch(() => {
console.log("Houston, there's a problem!")
})
...
const user = db.model('AuthorEntity');
const jack = user.find('[email protected]')
...
const jack = db.model('AuthorEntity');
jack.set('email', '[email protected]')
jack.delete();
The test suite relies on DynamoDB Local as a Docker image so Docker must be installed and running.
# start local dynamodb
$ npm run start
# run all tests
$ npm run test
# run tests in watch mode
$ npm run test: watch