dynotable-orm API: model() and the Model

What does model() return?

model(name, schema, options) defines a model and returns it. The model reads and writes items with get, create, update and delete, starts a query or a scan, sends batches, builds transaction entries and gives the CreateTable input of its table. Keys, indexes, dates and timestamps are resolved at model(), so a bad definition throws there, before any request.

import {model} from 'dynotable-orm';
import {z} from 'zod';

export const Order = model(
  'Order',
  z.object({
    customerId: z.string(),
    orderId: z.string(),
    status: z.enum(['open', 'paid']),
    total: z.number()
  }),
  {
    hashKey: 'customerId',
    rangeKey: 'orderId',
    indexes: {status: {name: 'byStatus', type: 'global', rangeKey: 'orderId'}}
  }
);

const order = await Order.get({customerId: 'c1', orderId: 'o1'}); // the item, or undefined
console.log(order?.total, Order.createTableInput().TableName);

This page lists model(), the Model methods, the model options and the type helpers that name a model's item, key and update types. Queries, scans and conditions are in queries and conditions; transactions, the client and the errors in transactions and client.

model()

function model<N, S, O>(name, schema, options?): Model<N, ModelTypesOf<S, O>>;

Defines a model. Keys, indexes, dates and timestamps are resolved now, so a bad definition throws here.

Type Parameters

Type ParameterDefault type
N extends string-
S extends StandardSchema<unknown, unknown>-
O extends ModelOptions<InferOutput<S>>object

Parameters

ParameterType
nameN
schemaS
options?O

Returns

Model<N, ModelTypesOf<S, O>>

Model type

Type Parameters

Type ParameterDefault type
Name extends stringstring
T extends TypesTypes

Constructors

Constructor

new Model(item): T["item"];

A deep copy of item as a plain object, as dynamoose's new Model(item) in fixtures and mocks. Nothing is validated or sent. Like dynamoose's item, it has a non-enumerable toJSON, so a test snapshot prints it as dynamoose's did.

Parameters

ParameterType
itemWriteItem<T>

Returns

T["item"]

Properties

PropertyModifierTypeDescription
~types?readonlyT-
hashKeyreadonlyT["hash"]-
namereadonlyNameThe name passed to model().
rangeKeyreadonly[T["range"]] extends [never] ? undefined : T["range"]-
tableNamereadonlystring${prefix}${name}${suffix}, read on every call, so a later setDefaults applies.
transactionreadonlyobjectEntries for transaction([...]): each resolves to the raw TransactWriteItem the request would hold.
transaction.conditionpublic(key, condition, options?) => Promise<{ ConditionCheck: ConditionCheck; }>-
transaction.createpublic(item, options?) => Promise<{ Put: Put; }>-
transaction.deletepublic(key, options?) => Promise<{ Delete: Delete; }>-
transaction.updatepublic(key, changes, options?) => Promise<{ Update: Update; }>; (item) => Promise<{ Update: Update; }>-

Methods

batchDelete()

batchDelete(keys, options?): Promise<{
  unprocessedItems: Record<string, unknown>[];
}>;

Deletes 25 keys per BatchWriteItem, retried as batchGet. unprocessedItems holds the stored keys.

Parameters

ParameterType
keysreadonly KeyInputOf<{ "~types"?: T; }>[]
options?CallOptions

Returns

Promise<{ unprocessedItems: Record<string, unknown>[]; }>


batchGet()

Call Signature

batchGet<A>(keys, options): Promise<BatchGetResponse<Pick<T["item"], T["hash"] | T["range"] | A[number]>>>;

Reads up to 100 keys per BatchGetItem, the chunks in parallel. Keys DynamoDB leaves unprocessed are sent again with backoff; those still unread at the end are in unprocessedKeys. Two equal keys throw before sending.

Type Parameters

Type Parameter
A extends readonly Attribute<T>[]

Parameters

ParameterType
keysreadonly KeyInputOf<{ "~types"?: T; }>[]
optionsBatchGetOptions<T["item"]> & object

Returns

Promise<BatchGetResponse<Pick<T["item"], T["hash"] | T["range"] | A[number]>>>

Call Signature

batchGet(keys, options?): Promise<BatchGetResponse<T["item"]>>;

Parameters

ParameterType
keysreadonly KeyInputOf<{ "~types"?: T; }>[]
options?BatchGetOptions<T["item"]>

Returns

Promise<BatchGetResponse<T["item"]>>


batchPut()

batchPut(items, options?): Promise<{
  unprocessedItems: Partial<T["input"]>[];
}>;

Writes each item as create with overwrite does, 25 per BatchWriteItem, retried as batchGet. Every item is validated before anything is sent.

Parameters

ParameterType
itemsreadonly Partial<T["input"]>[]
options?CallOptions

Returns

Promise<{ unprocessedItems: Partial<T["input"]>[]; }>


condition()

condition(): Condition<T["item"]>;

A Condition typed from the schema.

Returns

Condition<T["item"]>


create()

Call Signature

create(item, options): Promise<PutItemCommandInput>;

Resolves to the item as get would read it back.

Parameters

ParameterType
itemWriteItem<T>
optionsCreateOptions & object

Returns

Promise<PutItemCommandInput>

Call Signature

create(item, options?): Promise<T["item"]>;

Parameters

ParameterType
itemWriteItem<T>
options?CreateOptions

Returns

Promise<T["item"]>


createTableInput()

createTableInput(): CreateTableCommandInput;

The CreateTable input for this model's table, keys and indexes, on demand billing.

Returns

CreateTableCommandInput


delete()

Call Signature

delete(key, options): Promise<DeleteItemCommandInput>;

Parameters

ParameterType
keyKeyInputOf<{ "~types"?: T; }>
optionsDeleteOptions & object

Returns

Promise<DeleteItemCommandInput>

Call Signature

delete(key, options?): Promise<void>;

Parameters

ParameterType
keyKeyInputOf<{ "~types"?: T; }>
options?DeleteOptions

Returns

Promise<void>


extend()

extend<X>(methods): X & Model<Name, T>;

Adds methods to this model and returns it; this in each method is the model. A method added by an earlier extend() is replaced, as dynamoose's methods.set does; a built-in name throws a ConfigError. The type lists a replaced method's new signature first, then its old one (Omit would drop this).

Type Parameters

Type Parameter
X extends object

Parameters

ParameterType
methodsX & { [K in "query" | "scan" | "delete" | "hashKey" | "rangeKey" | "name" | "condition" | "~types" | "tableName" | "get" | "create" | "update" | "batchGet" | "batchPut" | "batchDelete" | "transaction" | "fromStored" | "withDefaults" | "createTableInput" | "extend"]: never } & ThisType<X & Model<Name, T>>

Returns

X & Model<Name, T>


fromStored()

fromStored(raw): T["item"];

Reads a stored item, as get does.

Parameters

ParameterType
rawStoredItem

Returns

T["item"]


get()

Call Signature

get(key, options): Promise<GetItemCommandInput>;

Parameters

ParameterType
keyKeyInputOf<{ "~types"?: T; }>
optionsGetOptions<T["item"]> & object

Returns

Promise<GetItemCommandInput>

Call Signature

get(key, options): Promise<Record<string, unknown> | undefined>;

Parameters

ParameterType
keyKeyInputOf<{ "~types"?: T; }>
optionsGetOptions<T["item"]> & object

Returns

Promise<Record<string, unknown> | undefined>

Call Signature

get<A>(key, options): Promise<Pick<T["item"], A[number]> | undefined>;

Type Parameters

Type Parameter
A extends readonly Attribute<T>[]

Parameters

ParameterType
keyKeyInputOf<{ "~types"?: T; }>
optionsGetOptions<T["item"]> & object

Returns

Promise<Pick<T["item"], A[number]> | undefined>

Call Signature

get(key, options?): Promise<T["item"] | undefined>;

Parameters

ParameterType
keyKeyInputOf<{ "~types"?: T; }>
options?GetOptions<T["item"]>

Returns

Promise<T["item"] | undefined>


query()

Call Signature

query(): Retriever<"query", T>;

query(field).eq(v)…, query({field: v}), or query() then where(). The index comes from the conditions (an index whose range key is in them, else the table, else the first hash match) unless using() names one.

Returns

Retriever<"query", T>

Call Signature

query<P>(key): Retriever<"query", T, T["item"], P>;

Type Parameters

Type Parameter
P extends string

Parameters

ParameterType
keyP

Returns

Retriever<"query", T, T["item"], P>

Call Signature

query(init): Retriever<"query", T>;

Parameters

ParameterType
initInit<T>

Returns

Retriever<"query", T>


scan()

Call Signature

scan(): Retriever<"scan", T>;

The same chain as query, without sort, plus parallel.

Returns

Retriever<"scan", T>

Call Signature

scan<P>(key): Retriever<"scan", T, T["item"], P>;

Type Parameters

Type Parameter
P extends string

Parameters

ParameterType
keyP

Returns

Retriever<"scan", T, T["item"], P>

Call Signature

scan(init): Retriever<"scan", T>;

Parameters

ParameterType
initInit<T>

Returns

Retriever<"scan", T>


update()

Call Signature

update(
   key,
   changes,
   options
): Promise<UpdateItemCommandInput>;

update(key, changes, options?), or update(item) with the key and the changes in one object. Plain fields are an implicit $SET. Resolves to the item returnValues asks for (ALL_NEW by default).

Parameters

ParameterType
keyKeyInputOf<{ "~types"?: T; }>
changesUpdateInput<T["input"]>
optionsUpdateOptions & object

Returns

Promise<UpdateItemCommandInput>

Call Signature

update(
   key,
   changes,
   options
): Promise<undefined>;

Parameters

ParameterType
keyKeyInputOf<{ "~types"?: T; }>
changesUpdateInput<T["input"]>
optionsUpdateOptions & object

Returns

Promise<undefined>

Call Signature

update(
   key,
   changes,
   options
): Promise<Partial<T["item"]> | undefined>;

Parameters

ParameterType
keyKeyInputOf<{ "~types"?: T; }>
changesUpdateInput<T["input"]>
optionsUpdateOptions & object

Returns

Promise<Partial<T["item"]> | undefined>

Call Signature

update(
   key,
   changes,
   options?
): Promise<T["item"]>;

Parameters

ParameterType
keyKeyInputOf<{ "~types"?: T; }>
changesUpdateInput<T["input"]>
options?UpdateOptions

Returns

Promise<T["item"]>

Call Signature

update(
   key,
   changes,
   options
): Promise<T["item"] | undefined>;

Writes the top-level attributes the schema does not declare too, as given: the changes are untyped.

Parameters

ParameterType
keyKeyInputOf<{ "~types"?: T; }>
changesRecord<string, any>
optionsUpdateOptions & object

Returns

Promise<T["item"] | undefined>

Call Signature

update(item): Promise<T["item"]>;

Parameters

ParameterType
itemExclude<KeyInputOf<{ "~types"?: T; }>, string | number | bigint | Uint8Array<ArrayBufferLike>> & UpdateInput<T["input"]>

Returns

Promise<T["item"]>


withDefaults()

withDefaults(item): T["item"];

A deep copy of item with the schema's defaults where a field is missing, as dynamoose's item.withDefaults(), but synchronous. Nothing is checked or sent.

Parameters

ParameterType
itemWriteItem<T>

Returns

T["item"]

ModelOptions type

Type Parameters

Type ParameterDefault type
ItemRecord<string, unknown>

Properties

PropertyTypeDescription
batchRetries?numberHow many times batchGet, batchPut and batchDelete send again what DynamoDB left unprocessed, with backoff. 0 returns it at once, as dynamoose does. Default 5
client?DynamoDBClientOverrides setClient for this model. A call's own client overrides both.
combine?{ [K in string]?: CombineDefinition<Field<Item>> }-
dates?{ [P in string]?: DateStorage }-
defaultDateStorage?DateStorageThe storage of a Date that dates and the field's own storage leave unset, timestamps included. Default 'milliseconds', as in dynamoose
hashKey?Field<Item>-
indexes?{ [K in string]?: IndexDefinition<Field<Item>> | readonly IndexDefinition<Field<Item>>[] }-
prefix?stringOverrides setDefaults for this model.
rangeKey?Field<Item>-
set?(item) => Record<string, unknown>The whole-item hook, on a deep copy. It runs on the stored-form item of a write, once on each $SET path of an update (wrapped in objects; a value it drops is removed), once on the whole key, and on each top-level condition value.
suffix?string-
timestamps?Timestamps-
unknownKeys?UnknownKeys'zod' follows Zod's own meaning of unknown keys. 'dynamoose' follows a Zod→dynamoose converter's saveUnknown rule: a record, any or custom field opens its parent at every depth. Default 'zod'

IndexDefinition type

A dynamoose index definition. A global index is hashed on its field; a local one uses its field as range key.

Type Parameters

Type ParameterDefault type
Field extends stringstring

Properties

PropertyTypeDescription
name?string-
project?boolean | readonly Field[]true projects all attributes, false only the keys, an array the listed attributes.
rangeKey?Field-
type?IndexType-

IndexType type

type IndexType = 'global' | 'local';

CombineDefinition type

Type Parameters

Type ParameterDefault type
Field extends stringstring

Properties

PropertyType
separator?string
sourcesreadonly Field[]

Timestamps type

type Timestamps =
  | boolean
  | {
      createdAt?: TimestampDefinition;
      updatedAt?: TimestampDefinition;
    };

TimestampDefinition type

Properties

PropertyType
name?string
storage?DateStorage

DateStorage type

type DateStorage = 'iso' | 'milliseconds' | 'seconds';

UnknownKeys type

type UnknownKeys = 'zod' | 'dynamoose';

CallOptions type

Extended by

Properties

PropertyType
abortSignal?AbortSignal
client?DynamoDBClient

ConditionFailureOptions type

'ALL_OLD': when the condition fails, DynamoDB returns the stored item, and the thrown SDK error (its class unchanged) carries it read back as get reads it, in item.

Extended by

Properties

PropertyType
returnValuesOnConditionCheckFailure?ReturnValuesOnConditionCheckFailure

GetOptions type

Extends

Type Parameters

Type ParameterDefault type
ItemRecord<string, unknown>

Properties

PropertyTypeDescriptionInherited from
abortSignal?AbortSignal-CallOptions.abortSignal
attributes?readonly (keyof Item & string)[]--
client?DynamoDBClient-CallOptions.client
consistent?boolean--
raw?booleanReturn the stored values, without converting them back.-
rawKey?booleanSend the key as given, skipping the key transforms.-
return?"item" | "request"--

CreateOptions type

'ALL_OLD': when the condition fails, DynamoDB returns the stored item, and the thrown SDK error (its class unchanged) carries it read back as get reads it, in item.

Extends

Properties

PropertyTypeDescriptionInherited from
abortSignal?AbortSignal-CallOptions.abortSignal
client?DynamoDBClient-CallOptions.client
condition?ConditionInput--
keepCreatedAt?booleanKeep the input's createdAt: save() semantics for an item that was read.-
overwrite?booleanReplace a stored item with the same key. Without it the write is conditional on the key not being stored.-
return?"item" | "request"--
returnValuesOnConditionCheckFailure?ReturnValuesOnConditionCheckFailure-ConditionFailureOptions.returnValuesOnConditionCheckFailure

DeleteOptions type

'ALL_OLD': when the condition fails, DynamoDB returns the stored item, and the thrown SDK error (its class unchanged) carries it read back as get reads it, in item.

Extends

Properties

PropertyTypeInherited from
abortSignal?AbortSignalCallOptions.abortSignal
client?DynamoDBClientCallOptions.client
condition?ConditionInput-
rawKey?boolean-
return?"request" | null-
returnValuesOnConditionCheckFailure?ReturnValuesOnConditionCheckFailureConditionFailureOptions.returnValuesOnConditionCheckFailure

StandardSchema type

The Standard Schema v1 interface (https://standardschema.dev), copied as the spec recommends.

Type Parameters

Type ParameterDefault type
Inputunknown
OutputInput

Properties

PropertyModifierType
~standardreadonlyobject
~standard.types?readonlyobject
~standard.types.inputreadonlyInput
~standard.types.outputreadonlyOutput
~standard.validatereadonly(value) => StandardResult<Output> | Promise<StandardResult<Output>>
~standard.vendorreadonlystring
~standard.versionreadonly1

WithMeta type

type WithMeta<S, M> = S & object;

A schema carrying field metadata M, in type only.

Type Parameters

Type Parameter
S
M

Type Declaration

NameType
~dynamoM

AnyModel type

Properties

PropertyModifierType
~types?readonlyAnyModelTypes

ModelTypes type

Type-only facts about a model. Range is never for a model with only a hash key.

Type Parameters

Type ParameterDefault type
Item-
Hash extends string-
Range extends string-
Indexes extends IndexTypesIndexTypes
InputItem

Properties

PropertyModifierTypeDescription
hashreadonlyHash-
indexesreadonlyIndexes-
inputreadonlyInputWhat a write parses: the schema's input, which a transform or a coercion makes wider than the item.
itemreadonlyItem-
rangereadonlyRange-

ModelTypesOf type

type ModelTypesOf<S, O> = ModelTypes<
  InferOutput<S>,
  O extends object ? H : MarkedField<S, 'hashKey'>,
  O extends object ? R : MarkedField<S, 'rangeKey'>,
  OptionIndexes<O> | FieldIndexes<S>,
  InferInput<S>
>;

Keys and indexes come from the options, else from the fields marked with hashKey()/rangeKey()/index().

Type Parameters

Type Parameter
S extends StandardSchema
O extends ModelOptions<InferOutput<S>>

IndexTypes type

A secondary index, in type only: its name, its key attributes and what it projects.

Properties

PropertyModifierType
keysreadonlystring
namereadonlystring
projectreadonlyboolean | readonly string[]

ItemOf type

type ItemOf<M> = TypesOf<M>['item'];

Type Parameters

Type Parameter
M extends AnyModel

KeyInputOf type

type KeyInputOf<M> =
  IsAny<TypesOf<M>> extends true
    ? any
    : [TypesOf<M>['range']] extends [never]
      ? KeyFields<ItemOf<M>, TypesOf<M>['hash']> | ItemOf<M>[TypesOf<M>['hash']]
      : KeyFields<ItemOf<M>, TypesOf<M>['hash'] | TypesOf<M>['range']>;

A key object, or a bare scalar for a model with only a hash key.

Type Parameters

Type Parameter
M extends AnyModel

Updated