betterddb
Version:
A definition-based DynamoDB wrapper library that provides a schema-driven and fully typesafe DAL.
84 lines • 3.21 kB
JavaScript
/* eslint-disable no-unused-vars */
import {} from "@aws-sdk/client-dynamodb";
import {} from "../betterddb.js";
import { PutCommand, TransactWriteCommand } from "@aws-sdk/lib-dynamodb";
export class CreateBuilder {
parent;
item;
extraTransactItems = [];
constructor(parent, item) {
this.parent = parent;
this.item = item;
}
async execute() {
const validated = this.parent.getSchema().parse(this.item);
if (this.extraTransactItems.length > 0) {
// Build our update transaction item.
const myTransactItem = this.toTransactPut();
// Combine with extra transaction items.
const allItems = [...this.extraTransactItems, myTransactItem];
await this.parent.getClient().send(new TransactWriteCommand({
TransactItems: allItems,
}));
// After transaction, retrieve the updated item.
const result = await this.parent.get(this.item).execute();
if (result === null) {
throw new Error("Item not found after transaction create");
}
return result;
}
else {
let finalItem = {
...this.item,
entityType: this.parent.getEntityType(),
};
if (this.parent.getTimestamps()) {
const now = new Date().toISOString();
finalItem = { ...finalItem, createdAt: now, updatedAt: now };
}
// Compute and merge primary key.
const computedKeys = this.parent.buildKey(validated);
finalItem = { ...finalItem, ...computedKeys };
// Compute and merge index attributes.
const indexAttributes = this.parent.buildIndexes(validated);
finalItem = { ...finalItem, ...indexAttributes };
await this.parent.getClient().send(new PutCommand({
TableName: this.parent.getTableName(),
Item: finalItem,
}));
return validated;
}
}
transactWrite(ops) {
if (Array.isArray(ops)) {
this.extraTransactItems.push(...ops);
}
else {
this.extraTransactItems.push(ops);
}
return this;
}
toTransactPut() {
const validated = this.parent.getSchema().parse(this.item);
let finalItem = {
...this.item,
entityType: this.parent.getEntityType(),
};
if (this.parent.getTimestamps()) {
const now = new Date().toISOString();
finalItem = { ...finalItem, createdAt: now, updatedAt: now };
}
// Compute and merge primary key.
const computedKeys = this.parent.buildKey(validated);
finalItem = { ...finalItem, ...computedKeys };
// Compute and merge index attributes.
const indexAttributes = this.parent.buildIndexes(validated);
finalItem = { ...finalItem, ...indexAttributes };
const putItem = {
TableName: this.parent.getTableName(),
Item: finalItem,
};
return { Put: putItem };
}
}
//# sourceMappingURL=create-builder.js.map