Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,66 @@ console.log(user?.plan, found.count);
`create` writes only when the key is not stored yet; pass `{overwrite: true}` to replace. `User.update` with
a wrong path or value type does not compile.

## Types from the schema

Define the shape of an item once, as a schema. You write no interface: `model()` infers every type of the
model from the schema and its marks. The same schema validates each whole-item write at runtime, and with
the Zod adapter each update too. When you change a field, the types and the validation change together.

```ts
import {
model,
type CreateInputOf,
type ItemOf,
type KeyInputOf,
type UpdateInputOf
} from 'dynotable-orm';
import {extendZod} from 'dynotable-orm/zod';
import {z} from 'zod';

extendZod(z);

export const Task = model(
'Task',
z.object({
projectId: z.string().hashKey(),
taskId: z.string().rangeKey(),
status: z.enum(['open', 'done']).default('open'),
points: z.number().int()
})
);

export type Task = ItemOf<typeof Task>; // {projectId: string; taskId: string; status: 'open' | 'done'; points: number}
export type TaskKey = KeyInputOf<typeof Task>; // {projectId: string; taskId: string}
export type TaskChanges = UpdateInputOf<typeof Task>; // each path with its value type, plus $SET, $ADD, ...
export type NewTask = CreateInputOf<typeof Task>; // status is optional here

const key: TaskKey = {projectId: 'p1', taskId: 't1'};
const draft: NewTask = {...key, points: 3};
await Task.create(draft);
const task: Task | undefined = await Task.get(key);
console.log(task?.status);

// @ts-expect-error: the key needs taskId, the range key
await Task.get({projectId: 'p1'});

// @ts-expect-error: points is a number
await Task.update(key, {points: '3'});
```

| type | what it is |
| ------------------------- | -------------------------------------------------------------------------------- |
| `ItemOf<typeof M>` | the item a read returns: the schema's output type, as `z.infer` gives it |
| `KeyInputOf<typeof M>` | the key `get`, `update` and `delete` take, from the hash key and range key marks |
| `UpdateInputOf<typeof M>` | what `update` takes: each path with its value type, and the update operators |
| `CreateInputOf<typeof M>` | what `create` takes: a `Partial` of the schema's input type |

A write takes the schema's input type and a read returns its output type, so a `.default()` field is
optional on `create` and always present on a read. `timestamps: true` adds no field to the types: declare
`createdAt` and `updatedAt` in the schema. Without the Zod adapter, the item type still comes from the schema,
and the keys and indexes come from the model options. The
[Zod adapter docs](https://dynotable.com/orm/zod#types-from-the-schema) have the full rules.

## Migrate from dynamoose to TypeScript and Zod

The codemod rewrites dynamoose call sites and converts each dynamoose `Schema` to a Zod schema plus model
Expand Down
1 change: 1 addition & 0 deletions packages/dynotable-orm/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export type {
CallOptions,
ConditionFailureOptions,
ConditionInput,
CreateInputOf,
CreateOptions,
DeleteOptions,
GetOptions,
Expand Down
7 changes: 6 additions & 1 deletion packages/dynotable-orm/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,12 @@ const projection = (project: IndexPlan['project']): Projection =>
? {ProjectionType: 'KEYS_ONLY'}
: {ProjectionType: 'INCLUDE', NonKeyAttributes: [...project]};

/** Defines a model. Keys, indexes, dates and timestamps are resolved now, so a bad definition throws here. */
/**
* Defines a model. Every type of the model is inferred from `schema` and `options`, so you write no interface:
* the item (`ItemOf`), the key (`KeyInputOf`), what `create` takes (`CreateInputOf`), the changes `update` takes
* (`UpdateInputOf`) and the index names.
* Keys, indexes, dates and timestamps are resolved now, so a bad definition throws here.
*/
export function model<
const N extends string,
S extends StandardSchema,
Expand Down
28 changes: 25 additions & 3 deletions packages/dynotable-orm/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ type FieldIndexes<S> = S extends {readonly shape: infer Shape}
}[keyof Shape & string]
: never;

/** Keys and indexes come from the options, else from the fields marked with `hashKey()`/`rangeKey()`/`index()`. */
/**
* The types `model()` infers from schema `S` and options `O`. The item and the input come from the schema. Keys
* and indexes come from the options, else from the fields marked with `hashKey()`/`rangeKey()`/`index()`.
*/
export type ModelTypesOf<
S extends StandardSchema,
O extends ModelOptions<InferOutput<S>>
Expand All @@ -124,17 +127,36 @@ export interface AnyModel {
export type TypesOf<M extends AnyModel> = NonNullable<M['~types']>;
type KeyFields<T, K> = {[P in K & keyof T]-?: Exclude<T[P], undefined>};

/**
* The item a read returns, as `ItemOf<typeof M>`: the schema's output type, as `z.infer<typeof schema>` gives it.
* A write takes the schema's input type, which `.default()`, `.transform()` and `z.coerce` make differ.
*/
export type ItemOf<M extends AnyModel> = TypesOf<M>['item'];

/** A key object, or a bare scalar for a model with only a hash key. */
/**
* The key `get`, `update` and `delete` take, as `KeyInputOf<typeof M>`: an object with the hash key and the range
* key. A model with only a hash key also takes the bare value. The key attributes come from the field marks or
* from the `hashKey` and `rangeKey` options.
*/
export type KeyInputOf<M extends AnyModel> =
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']>;

/** What `update` takes: the schema's input, which it parses. */
/**
* What `create` takes, as `CreateInputOf<typeof M>`: a `Partial` of the schema's input, which it parses. A field
* with `.default()` is optional here and present on `ItemOf`. A missing required field compiles, and the runtime
* check rejects it.
*/
export type CreateInputOf<M extends AnyModel> = Partial<TypesOf<M>['input']>;

/**
* The changes `update` takes, as `UpdateInputOf<typeof M>`. Each top-level field is an implicit `$SET` with its
* input type. `$SET`, `$REMOVE`, `$ADD` and `$DELETE` take paths and values typed by the schema. `$ADD` takes only
* a number, a Set or a list path.
*/
export type UpdateInputOf<M extends AnyModel> = UpdateInput<TypesOf<M>['input']>;

export type IsAny<T> = 0 extends 1 & T ? true : false;
Expand Down
16 changes: 15 additions & 1 deletion packages/dynotable-orm/tests/model.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import {describe, expectTypeOf, it} from 'vitest';
import {z} from 'zod';
import type {AttributeValue} from '@aws-sdk/client-dynamodb';
import {type Condition, type ItemOf, type KeyInputOf, model, transaction} from '../src/index.js';
import {
type Condition,
type CreateInputOf,
type ItemOf,
type KeyInputOf,
model,
transaction
} from '../src/index.js';
import {hashKey} from '../src/zod/index.js';

const schema = z.object({
Expand Down Expand Up @@ -30,6 +37,13 @@ describe('model types', () => {
expectTypeOf<KeyInputOf<typeof Composite>>().toEqualTypeOf<{id: string; sk: number}>();
});

// CreateInputOf is a separate alias of the create parameter type, so this pins the two together.
it('names what create takes', () => {
expectTypeOf<CreateInputOf<typeof Composite>>().toEqualTypeOf<
Parameters<typeof Composite.create>[0]
>();
});

it('narrows the item to the requested attributes', async () => {
expectTypeOf(await Composite.get({id: 'a', sk: 1}, {attributes: ['id', 'n']})).toEqualTypeOf<
Pick<Item, 'id' | 'n'> | undefined
Expand Down
16 changes: 16 additions & 0 deletions packages/dynotable-orm/tests/types.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {describe, expectTypeOf, it} from 'vitest';
import {z} from 'zod';
import type {
CreateInputOf,
ItemOf,
KeyInputOf,
ModelOptions,
Expand Down Expand Up @@ -36,6 +37,21 @@ describe('ItemOf', () => {
});
});

describe('CreateInputOf', () => {
// create parses its input, so a field whose input differs from its output takes the input type here.
it('is a Partial of the schema input, not of the item', () => {
const coerced = typed(
z.object({id: z.string(), n: z.string().transform(Number), on: z.boolean().default(false)}),
{hashKey: 'id'}
);
expectTypeOf<CreateInputOf<typeof coerced>>().toEqualTypeOf<{
id?: string;
n?: string;
on?: boolean | undefined;
}>();
});
});

describe('KeyInputOf', () => {
it('accepts a scalar only for a model with only a hash key', () => {
expectTypeOf<KeyInputOf<typeof hashOnly>>().toEqualTypeOf<{id: string} | string>();
Expand Down
Loading