Skip to content

Instantly share code, notes, and snippets.

@ryanvade
Last active November 17, 2019 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanvade/544cf46f343d705268a4f084a84502a8 to your computer and use it in GitHub Desktop.
Save ryanvade/544cf46f343d705268a4f084a84502a8 to your computer and use it in GitHub Desktop.
DynamoDB ODM API Example
import { Survey, OpenState, ClosedState, DeletedState } from "somewhere/Survey.ts";
// make a new one
let survey = new Survey();
// save it
await survey.save();
// Get from DB
survey = await Survey.get(survey.id);
// Transition the state to another state
await survey.transitionTo(OpenState);
// Get fro DB
let openSurvey = await Survey.get(survey.id);
// Transition teh state to another state
await openSurvey.transitionTo(ClosedState);
// Get all from DB
let surveys = await Survey.batchGet();
// Transition all of them
await Promise.all(surveys.map((survey: Survey) => {
return survey.transitionTo(DeletedState);
}));
// Survey.ts
import { Table, HashKey, RangeKey, Attribute, GlobalSecondaryIndex } from "@foobar/core";
import { Stateful, StateAttribute, State, DefaultState } from "@foobar/stateful";
export class CreatedState extends State {}
export class OpenState extends State {}
export class ClosedState extends State {}
export class DisabledState extends State {}
export class DeletedState extends State {}
@Stateful()
export class Survey extends Table {
@HashKey({ uuid: true })
id: string;
@Attribute()
allMembers: boolean;
@Attribute()
allowIgnore: boolean;
@Attribute()
buttonText: string;
@Attribute()
completeText: string;
@GlobalSecondaryIndex({ name: "orgIndex", project: true, throughput: 1})
org: string;
@Attribute()
members: string[];
@GlobalSecondaryIndex({ name: "sendTimeIndex", rangeKey: "sendTime", project: true, throughput: 1 })
sendDate: string;
@Attribute()
sendTime: number;
@StateAttribute()
state: string;
protected states() {
return {
DefaultState: [ CreatedState, DeletedState ],
CreatedState: [ OpenState, DeletedState, DisabledState ],
OpenState: [ ClosedState ],
ClosedState: [ OpenState, DisabledState, DeletedState ],
DisabledState: [ OpenState, DeletedState ],
DeletedState: [ CreatedState ]
};
}
// Called before any transition...has default implementation
protected async beforeTransition(previous: State, next: State) {
switch (next) {
case DeletedState: {
this.members = [];
}
}
await this.save();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment