Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Last active October 14, 2021 17:41
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 joyrexus/7f73ccd72693ed99b5a76fe0315bb2ce to your computer and use it in GitHub Desktop.
Save joyrexus/7f73ccd72693ed99b5a76fe0315bb2ce to your computer and use it in GitHub Desktop.
demonstrating attempts to upsert with electrodb
{
"name": "upsert-example",
"version": "1.0.0",
"description": "Demonstrating attempts to upsert records with electrodb",
"dependencies": {
"aws-sdk": "2.544.0",
"electrodb": "0.9.52"
}
}
const DynamoDB = require("aws-sdk/clients/dynamodb");
const { Entity } = require("electrodb");
TransactionModel = {
model: {
version: "1",
service: "transactions",
entity: "transaction",
},
attributes: {
accountId: {
type: "string",
},
transactionId: {
type: "string",
},
amount: {
type: "number",
},
},
indexes: {
transaction: {
pk: {
field: "PK",
facets: ["accountId"],
},
sk: {
field: "SK",
facets: ["transactionId"],
},
},
},
};
const table = "MY_TABLE_NAME";
const client = new DynamoDB.DocumentClient();
const txn = new Entity(TransactionModel, { client, table });
const transaction = {
accountId: "100",
transactionId: "1",
amount: 25,
};
(async () => {
let result;
// attempt to upsert a transaction record with `update`
await txn.delete(transaction).go();
await txn.update(transaction).set({ amount: 25 }).go();
result = await txn.get(transaction).go({ includeKeys: true });
console.log(JSON.stringify(result, null, 4));
/*
{
"amount": 25,
"SK": "$transaction_1#transactionid_1",
"PK": "$transactions#accountid_100"
}
*/
// compare with transaction record resulting from a `put`
await txn.delete(transaction).go();
await txn.put(transaction).go();
result = await txn.get(transaction).go({ includeKeys: true });
console.log(JSON.stringify(result, null, 4));
/*
{
"__edb_e__": "transaction",
"__edb_v__": "1",
"accountId": "100",
"amount": 25,
"SK": "$transaction_1#transactionid_1",
"PK": "$transactions#accountid_100",
"transactionId": "1"
}
*/
// attempt to upsert a transaction record with `update` part deux
await txn.delete(transaction).go();
await txn.update(transaction).set(transaction).go();
/*
Error: Attribute accountId is Read-Only and cannot be updated
at Schema.checkUpdate (/upsert_example/node_modules/electrodb/src/schema.js:394:11)
at Object.action (/upsert_example/node_modules/electrodb/src/clauses.js:193:37)
at Object.current.<computed> [as set] (/upsert_example//node_modules/electrodb/src/entity.js:384:34)
at /upsert_example/upsert.js:66:35
*/
})().catch(console.error);
@joyrexus
Copy link
Author

Notice how the accountId and transactionId attributes are autogenerated when using put, but not with update.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment