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 Parameter | Default type |
|---|---|
N extends string | - |
S extends StandardSchema<unknown, unknown> | - |
O extends ModelOptions<InferOutput<S>> | object |
Parameters
| Parameter | Type |
|---|---|
name | N |
schema | S |
options? | O |
Returns
Model<N, ModelTypesOf<S, O>>
Model type
Type Parameters
| Type Parameter | Default type |
|---|---|
Name extends string | string |
T extends Types | Types |
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
| Parameter | Type |
|---|---|
item | WriteItem<T> |
Returns
T["item"]
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
~types? | readonly | T | - |
hashKey | readonly | T["hash"] | - |
name | readonly | Name | The name passed to model(). |
rangeKey | readonly | [T["range"]] extends [never] ? undefined : T["range"] | - |
tableName | readonly | string | ${prefix}${name}${suffix}, read on every call, so a later setDefaults applies. |
transaction | readonly | object | Entries for transaction([...]): each resolves to the raw TransactWriteItem the request would hold. |
transaction.condition | public | (key, condition, options?) => Promise<{ ConditionCheck: ConditionCheck; }> | - |
transaction.create | public | (item, options?) => Promise<{ Put: Put; }> | - |
transaction.delete | public | (key, options?) => Promise<{ Delete: Delete; }> | - |
transaction.update | public | (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
| Parameter | Type |
|---|---|
keys | readonly 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
| Parameter | Type |
|---|---|
keys | readonly KeyInputOf<{ "~types"?: T; }>[] |
options | BatchGetOptions<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
| Parameter | Type |
|---|---|
keys | readonly 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
| Parameter | Type |
|---|---|
items | readonly 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
| Parameter | Type |
|---|---|
item | WriteItem<T> |
options | CreateOptions & object |
Returns
Promise<PutItemCommandInput>
Call Signature
create(item, options?): Promise<T["item"]>;Parameters
| Parameter | Type |
|---|---|
item | WriteItem<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
| Parameter | Type |
|---|---|
key | KeyInputOf<{ "~types"?: T; }> |
options | DeleteOptions & object |
Returns
Promise<DeleteItemCommandInput>
Call Signature
delete(key, options?): Promise<void>;Parameters
| Parameter | Type |
|---|---|
key | KeyInputOf<{ "~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
| Parameter | Type |
|---|---|
methods | X & { [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
| Parameter | Type |
|---|---|
raw | StoredItem |
Returns
T["item"]
get()
Call Signature
get(key, options): Promise<GetItemCommandInput>;Parameters
| Parameter | Type |
|---|---|
key | KeyInputOf<{ "~types"?: T; }> |
options | GetOptions<T["item"]> & object |
Returns
Promise<GetItemCommandInput>
Call Signature
get(key, options): Promise<Record<string, unknown> | undefined>;Parameters
| Parameter | Type |
|---|---|
key | KeyInputOf<{ "~types"?: T; }> |
options | GetOptions<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
| Parameter | Type |
|---|---|
key | KeyInputOf<{ "~types"?: T; }> |
options | GetOptions<T["item"]> & object |
Returns
Promise<Pick<T["item"], A[number]> | undefined>
Call Signature
get(key, options?): Promise<T["item"] | undefined>;Parameters
| Parameter | Type |
|---|---|
key | KeyInputOf<{ "~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
| Parameter | Type |
|---|---|
key | P |
Returns
Retriever<"query", T, T["item"], P>
Call Signature
query(init): Retriever<"query", T>;Parameters
| Parameter | Type |
|---|---|
init | Init<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
| Parameter | Type |
|---|---|
key | P |
Returns
Retriever<"scan", T, T["item"], P>
Call Signature
scan(init): Retriever<"scan", T>;Parameters
| Parameter | Type |
|---|---|
init | Init<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
| Parameter | Type |
|---|---|
key | KeyInputOf<{ "~types"?: T; }> |
changes | UpdateInput<T["input"]> |
options | UpdateOptions & object |
Returns
Promise<UpdateItemCommandInput>
Call Signature
update(
key,
changes,
options
): Promise<undefined>;Parameters
| Parameter | Type |
|---|---|
key | KeyInputOf<{ "~types"?: T; }> |
changes | UpdateInput<T["input"]> |
options | UpdateOptions & object |
Returns
Promise<undefined>
Call Signature
update(
key,
changes,
options
): Promise<Partial<T["item"]> | undefined>;Parameters
| Parameter | Type |
|---|---|
key | KeyInputOf<{ "~types"?: T; }> |
changes | UpdateInput<T["input"]> |
options | UpdateOptions & object |
Returns
Promise<Partial<T["item"]> | undefined>
Call Signature
update(
key,
changes,
options?
): Promise<T["item"]>;Parameters
| Parameter | Type |
|---|---|
key | KeyInputOf<{ "~types"?: T; }> |
changes | UpdateInput<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
| Parameter | Type |
|---|---|
key | KeyInputOf<{ "~types"?: T; }> |
changes | Record<string, any> |
options | UpdateOptions & object |
Returns
Promise<T["item"] | undefined>
Call Signature
update(item): Promise<T["item"]>;Parameters
| Parameter | Type |
|---|---|
item | Exclude<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
| Parameter | Type |
|---|---|
item | WriteItem<T> |
Returns
T["item"]
ModelOptions type
Type Parameters
| Type Parameter | Default type |
|---|---|
Item | Record<string, unknown> |
Properties
| Property | Type | Description |
|---|---|---|
batchRetries? | number | How 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? | DynamoDBClient | Overrides setClient for this model. A call's own client overrides both. |
combine? | { [K in string]?: CombineDefinition<Field<Item>> } | - |
dates? | { [P in string]?: DateStorage } | - |
defaultDateStorage? | DateStorage | The 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? | string | Overrides 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 Parameter | Default type |
|---|---|
Field extends string | string |
Properties
| Property | Type | Description |
|---|---|---|
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 Parameter | Default type |
|---|---|
Field extends string | string |
Properties
| Property | Type |
|---|---|
separator? | string |
sources | readonly Field[] |
Timestamps type
type Timestamps =
| boolean
| {
createdAt?: TimestampDefinition;
updatedAt?: TimestampDefinition;
};TimestampDefinition type
Properties
| Property | Type |
|---|---|
name? | string |
storage? | DateStorage |
DateStorage type
type DateStorage = 'iso' | 'milliseconds' | 'seconds';UnknownKeys type
type UnknownKeys = 'zod' | 'dynamoose';CallOptions type
Extended by
Properties
| Property | Type |
|---|---|
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
| Property | Type |
|---|---|
returnValuesOnConditionCheckFailure? | ReturnValuesOnConditionCheckFailure |
GetOptions type
Extends
Type Parameters
| Type Parameter | Default type |
|---|---|
Item | Record<string, unknown> |
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
abortSignal? | AbortSignal | - | CallOptions.abortSignal |
attributes? | readonly (keyof Item & string)[] | - | - |
client? | DynamoDBClient | - | CallOptions.client |
consistent? | boolean | - | - |
raw? | boolean | Return the stored values, without converting them back. | - |
rawKey? | boolean | Send 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
| Property | Type | Description | Inherited from |
|---|---|---|---|
abortSignal? | AbortSignal | - | CallOptions.abortSignal |
client? | DynamoDBClient | - | CallOptions.client |
condition? | ConditionInput | - | - |
keepCreatedAt? | boolean | Keep the input's createdAt: save() semantics for an item that was read. | - |
overwrite? | boolean | Replace 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
| Property | Type | Inherited from |
|---|---|---|
abortSignal? | AbortSignal | CallOptions.abortSignal |
client? | DynamoDBClient | CallOptions.client |
condition? | ConditionInput | - |
rawKey? | boolean | - |
return? | "request" | null | - |
returnValuesOnConditionCheckFailure? | ReturnValuesOnConditionCheckFailure | ConditionFailureOptions.returnValuesOnConditionCheckFailure |
StandardSchema type
The Standard Schema v1 interface (https://standardschema.dev), copied as the spec recommends.
Type Parameters
| Type Parameter | Default type |
|---|---|
Input | unknown |
Output | Input |
Properties
| Property | Modifier | Type |
|---|---|---|
~standard | readonly | object |
~standard.types? | readonly | object |
~standard.types.input | readonly | Input |
~standard.types.output | readonly | Output |
~standard.validate | readonly | (value) => StandardResult<Output> | Promise<StandardResult<Output>> |
~standard.vendor | readonly | string |
~standard.version | readonly | 1 |
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
| Name | Type |
|---|---|
~dynamo | M |
AnyModel type
Properties
| Property | Modifier | Type |
|---|---|---|
~types? | readonly | AnyModelTypes |
ModelTypes type
Type-only facts about a model. Range is never for a model with only a hash key.
Type Parameters
| Type Parameter | Default type |
|---|---|
Item | - |
Hash extends string | - |
Range extends string | - |
Indexes extends IndexTypes | IndexTypes |
Input | Item |
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
hash | readonly | Hash | - |
indexes | readonly | Indexes | - |
input | readonly | Input | What a write parses: the schema's input, which a transform or a coercion makes wider than the item. |
item | readonly | Item | - |
range | readonly | Range | - |
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
| Property | Modifier | Type |
|---|---|---|
keys | readonly | string |
name | readonly | string |
project | readonly | boolean | 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 |