Skip to content

Instantly share code, notes, and snippets.

@tywalch
Created December 29, 2023 22:39
Show Gist options
  • Save tywalch/1d31716794e440cd47c362ee2277439d to your computer and use it in GitHub Desktop.
Save tywalch/1d31716794e440cd47c362ee2277439d to your computer and use it in GitHub Desktop.
ElectroDB Transactions across tables
process.env.AWS_NODEJS_CONNECTION_REUSE_ENABLED = "1";
import { Entity, ElectroEventListener, Service, createWriteTransaction, createGetTransaction } from 'electrodb';
import { DocumentClient } from "aws-sdk/clients/dynamodb";
const table = "electro";
const configuration = {
endpoint: "http://localhost:8000",
region: "us-east-1",
};
const client = new DocumentClient(configuration);
const Thing = new Entity({
model: {
entity: "thing",
service: "things",
version: "1",
},
attributes: {
thingId: {
type: "string",
},
ownerId: {
type: "string",
},
name: {
type: "string",
},
},
indexes: {
things: {
pk: {
field: "pk",
composite: ["ownerId"],
},
sk: {
field: "sk",
composite: ["thingId"],
}
}
}
}, { table, client });
const ThingService = new Service({ Thing }, );
function main() {
// with functions
const params1 = createGetTransaction({ Thing }, ({ Thing }) => [
Thing.get({ thingId: '001', ownerId: '555' }).commit({ table: 'override-table-one' }),
Thing.get({ thingId: '001', ownerId: '666' }).commit({ table: 'override-table-two' }),
]).params();
console.log('with createGetTransaction:', JSON.stringify(params1, null, 4));
const params2 = createWriteTransaction({ Thing }, ({ Thing }) => [
Thing.create({ thingId: '001', ownerId: '555', name: 'object' }).commit({ table: 'override-table-one' }),
Thing.create({ thingId: '001', ownerId: '666', name: 'object' }).commit({ table: 'override-table-two' }),
]).params();
console.log('with createWriteTransaction:', JSON.stringify(params2, null, 4));
const params3 = ThingService.transaction.write(({ Thing }) => [
Thing.create({ thingId: '001', ownerId: '555', name: 'object' }).commit({ table: 'override-table-one' }),
Thing.create({ thingId: '001', ownerId: '666', name: 'object' }).commit({ table: 'override-table-two' }),
]).params({});
console.log('with ThingService.transaction.write:', JSON.stringify(params3, null, 4));
const params4 = ThingService.transaction.get(({ Thing }) => [
Thing.get({ thingId: '001', ownerId: '555' }).commit({ table: 'override-table-one' }),
Thing.get({ thingId: '001', ownerId: '666' }).commit({ table: 'override-table-two' }),
]).params();
console.log('with ThingService.transaction.get:', JSON.stringify(params3, null, 4));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment