Skip to content

Instantly share code, notes, and snippets.

@mariobittencourt
Created June 16, 2020 00:36
Show Gist options
  • Save mariobittencourt/8341b6d92ba4c3dc31f0859010c2a1f3 to your computer and use it in GitHub Desktop.
Save mariobittencourt/8341b6d92ba4c3dc31f0859010c2a1f3 to your computer and use it in GitHub Desktop.
Example with private constructor
import "reflect-metadata";
import {Model, PartitionKey, Property, CollectionProperty} from '@shiftcoders/dynamo-easy';
import { DynamoStore } from '@shiftcoders/dynamo-easy';
import { v4 } from "uuid";
abstract class DomainEvent {
protected constructor(public readonly type: string, public readonly aggregateId: string, public readonly createdAt: string) {
}
}
@Model()
class OrderCreated extends DomainEvent {
constructor(aggregateId: string, public readonly customer: string, public readonly deliveryAddress: string, public readonly items: Array<Item>, createdAt: string) {
super('OrderCreated', aggregateId, createdAt);
}
}
@Model()
class Item {
@Property()
public readonly itemId: string;
@Property()
public readonly quantity: number;
constructor(itemId: string, quantity: number) {
this.itemId = itemId;
this.quantity = quantity;
}
}
@Model({tableName:'orders'})
class Order {
@PartitionKey()
private orderId: string;
@Property()
private customer: string;
@Property()
private deliveryAddress: string;
@CollectionProperty({itemType: Item})
private items: Array<Item>;
@CollectionProperty({itemType: OrderCreated})
private events: Array<DomainEvent>;
getEvents(): Array<DomainEvent> {
return this.events;
}
private constructor(orderId: string, customer: string, deliveryAddress: string, items: Array<Item>) {
this.orderId = orderId;
this.customer = customer;
this.deliveryAddress = deliveryAddress;
this.items = items;
this.events = new Array<DomainEvent>();
this.events.push(new OrderCreated(orderId, customer, deliveryAddress, items, (new Date().toISOString())));
}
public static create(orderId: string, customer: string, deliveryAddress: string, items: Array<Item>): Order {
return new Order(orderId, customer, deliveryAddress, items);
}
}
const clientConfiguration = {region: 'us-east-1'};
const store = new DynamoStore(Order, new DynamoDB(clientConfiguration));
(async () => {
try {
const id = v4();
let items = new Array<Item>();
items.push(new Item(v4(), 10));
const order = Order.create(id, 'Mr Buy More', 'My place.com', items);
const result = await store.put(order).exec();
console.log('Saved');
let newOrder : Order = await store.query().wherePartitionKey(id).execSingle();
console.log(newOrder);
} catch (e) {
console.log(e);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment