dynotable-orm API: transactions, client and errors

How do transactions work in dynotable-orm?

transaction([...]) sends one TransactWriteItems request. Its entries come from each model's transaction.create, update, delete and condition, mixed with raw TransactItems. It throws before sending for more than 100 entries or for two entries on one key. A canceled transaction re-throws the SDK error unchanged, with reasons: one code per entry.

import {DynamoDBClient} from '@aws-sdk/client-dynamodb';
import {isConditionalCheckFailed, model, setClient, setDefaults, transaction} from 'dynotable-orm';
import {z} from 'zod';

setClient(new DynamoDBClient({region: 'eu-west-1'}));
setDefaults({prefix: 'prod-'}); // every table name is now prod-<name>

const Stock = model('Stock', z.object({sku: z.string(), count: z.number()}), {hashKey: 'sku'});

try {
  await Stock.create({sku: 'a', count: 1});
} catch (e) {
  if (!isConditionalCheckFailed(e)) throw e; // 'a' is already stored
}

try {
  await transaction([
    Stock.transaction.update({sku: 'a'}, {$ADD: {count: -1}}),
    Stock.transaction.create({sku: 'b', count: 1})
  ]);
} catch (e) {
  console.log((e as {reasons?: string[]}).reasons); // e.g. ['None', 'ConditionalCheckFailed']
}

ConfigError, ExpressionError, ValidationError and MarshallError are thrown before a request is sent: a model definition that cannot work, a request DynamoDB would reject, an item the schema rejects, and a value DynamoDB cannot store. toJSON and converter keep two dynamoose helpers.

transaction()

Call Signature

function transaction(items, options): Promise<TransactWriteItemsCommandInput>;

Sends TransactWriteItems with the entries of the models' transaction.*, mixed with raw TransactItems. It throws before sending for more than 100 entries or two entries on one key. The client is the client option, else getClient(). A canceled transaction re-throws the SDK error unchanged, with reasons: the CancellationReasons code of each entry, in order ('None' for the entries that passed), and items: the stored item each entry's failed condition returned (ReturnValuesOnConditionCheckFailure), read by its model, else undefined.

Parameters

ParameterType
itemsreadonly (TransactWriteItem | Promise<TransactWriteItem>)[]
optionsTransactionOptions & object

Returns

Promise<TransactWriteItemsCommandInput>

Call Signature

function transaction(items, options?): Promise<void>;

Sends TransactWriteItems with the entries of the models' transaction.*, mixed with raw TransactItems. It throws before sending for more than 100 entries or two entries on one key. The client is the client option, else getClient(). A canceled transaction re-throws the SDK error unchanged, with reasons: the CancellationReasons code of each entry, in order ('None' for the entries that passed), and items: the stored item each entry's failed condition returned (ReturnValuesOnConditionCheckFailure), read by its model, else undefined.

Parameters

ParameterType
itemsreadonly (TransactWriteItem | Promise<TransactWriteItem>)[]
options?TransactionOptions

Returns

Promise<void>

orm

const orm: object;

The lib's top-level calls as one object, for test spies: vi.spyOn(orm, 'transaction') sees every transaction() call. A named ESM import cannot be spied on, as vi.spyOn(dynamoose, 'transaction') could.

Type Declaration

NameType
transaction()(items, options?) => Promise<unknown>

TransactionOptions type

Extends

Properties

PropertyTypeInherited from
abortSignal?AbortSignalCallOptions.abortSignal
client?DynamoDBClientCallOptions.client
return?"request"-

BatchGetOptions type

Extends

Type Parameters

Type ParameterDefault type
ItemRecord<string, unknown>

Properties

PropertyTypeDescriptionInherited from
abortSignal?AbortSignal-CallOptions.abortSignal
attributes?readonly (keyof Item & string)[]The key attributes are read too, so each item can take its key's position.-
client?DynamoDBClient-CallOptions.client
consistent?boolean--

BatchGetResponse type

type BatchGetResponse<T> = T[] & object;

The items found, in the order of the keys. unprocessedKeys holds the stored keys DynamoDB left unread after the retries.

Type Parameters

Type Parameter
T

Type Declaration

NameType
unprocessedKeysRecord<string, unknown>[]

setClient()

function setClient(c?): void;

The client every model uses, unless the model option or a call's client gives another. Without an argument, the next call gets a new client with the SDK's default configuration, as dynamoose's aws.ddb.revert().

Parameters

ParameterType
c?DynamoDBClient

Returns

void

getClient()

function getClient(): DynamoDBClient;

Created on first use with the SDK's default configuration, when setClient was not called.

Returns

DynamoDBClient

setDefaults()

function setDefaults(d): void;

The table-name prefix and suffix of every model that does not set its own. Replaces the earlier defaults, as dynamoose's Table.defaults.set.

Parameters

ParameterType
dDefaults

Returns

void

isConditionalCheckFailed()

function isConditionalCheckFailed(e): boolean;

True for the SDK error of a write whose condition failed. Matched by name, so any SDK copy's error class counts.

Parameters

ParameterType
eunknown

Returns

boolean

ConfigError

A model definition that cannot work. Thrown by model(), extend(), createTableInput() and extendZod(), before any request is sent. Also thrown by the first call that parses a key, condition or query value whose field has an async check or transform: those values are parsed synchronously, and only a call shows that a check is async.

Extends

  • Error

Constructors

Constructor

new ConfigError(message?): ConfigError;

Parameters

ParameterType
message?string

Returns

ConfigError

Inherited from

Error.constructor

Constructor

new ConfigError(message?, options?): ConfigError;

Parameters

ParameterType
message?string
options?ErrorOptions

Returns

ConfigError

Inherited from

Error.constructor

Properties

PropertyModifierTypeDefault valueOverrides
namereadonly"ConfigError"'ConfigError'Error.name

ExpressionError

A path, an update, a condition, a key, a batch or a transaction that DynamoDB would reject. Thrown before any request is sent.

Extends

  • Error

Constructors

Constructor

new ExpressionError(message?): ExpressionError;

Parameters

ParameterType
message?string

Returns

ExpressionError

Inherited from

Error.constructor

Constructor

new ExpressionError(message?, options?): ExpressionError;

Parameters

ParameterType
message?string
options?ErrorOptions

Returns

ExpressionError

Inherited from

Error.constructor

Properties

PropertyModifierTypeDefault valueOverrides
namereadonly"ExpressionError"'ExpressionError'Error.name

ValidationError

The schema rejected an item. path is the path of the first issue. A value outside an enum and a value of the wrong type are told in dynamoose's words, which callers and tests match: status must equal ["A","B"], but is set to C, Expected note to be of type string, instead found type null.. Any other issue keeps the schema's message.

Extends

  • Error

Constructors

Constructor

new ValidationError(issues, valueAt?): ValidationError;

valueAt reads the rejected value at an issue's path, for the dynamoose wording.

Parameters

ParameterType
issuesreadonly StandardIssue[]
valueAt?(path) => unknown

Returns

ValidationError

Overrides

Error.constructor

Properties

PropertyModifierTypeDefault valueOverrides
issuesreadonlyreadonly StandardIssue[]undefined-
namereadonly"ValidationError"'ValidationError'Error.name
pathreadonlyreadonly PropertyKey[]undefined-

MarshallError

Extends

  • Error

Constructors

Constructor

new MarshallError(reason): MarshallError;

Parameters

ParameterType
reasonstring

Returns

MarshallError

Overrides

Error.constructor

Properties

PropertyModifierTypeDefault valueOverrides
namereadonly"MarshallError"'MarshallError'Error.name
pathreadonlyPathSegment[][]-
reasonreadonlystringundefined-

toJSON()

Call Signature

function toJSON(x): Record<string, any>[];

dynamoose's item.toJSON(): a JSON round trip, so a Date becomes its ISO string and a Set an empty object.

Parameters

ParameterType
xreadonly object[]

Returns

Record<string, any>[]

Call Signature

function toJSON(x): Record<string, any>;

dynamoose's item.toJSON(): a JSON round trip, so a Date becomes its ISO string and a Set an empty object.

Parameters

ParameterType
xobject

Returns

Record<string, any>

converter

const converter: object;

The @aws-sdk/util-dynamodb functions that dynamoose's aws.converter() returns, with their options.

Type Declaration

NameTypeDescription
convertToAttr()(data, options?) => AttributeValueConvert a JavaScript value to its equivalent DynamoDB AttributeValue type.
marshall(){ (data, options?): NULLMember; (data, options?): NSMember; (data, options?): SSMember; (data, options?): BSMember; (data, options?): BMember; (data, options?): BOOLMember; (data, options?): NMember; (data, options?): SMember; (data, options?): BOOLMember; <O>(data, options): LMember; <O>(data, options): AttributeValue[]; <O>(data, options): LMember | AttributeValue[]; (data, options?): AttributeValue[]; <O>(data, options): MMember; <O>(data, options): Record<string, AttributeValue>; <O>(data, options): MMember | Record<string, AttributeValue>; (data, options?): Record<string, AttributeValue>; (data, options?): any; (data, options?): $UnknownMember; }Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. Convert a JavaScript object into a DynamoDB record. This signature will be unmatchable but is included for information.
unmarshall()(data, options?) => Record<string, NativeAttributeValue>Convert a DynamoDB record into a JavaScript object.

Updated