Skip to content

Commit

Permalink
Merge pull request #188 from oliver-oloughlin/add-module-docs
Browse files Browse the repository at this point in the history
Add module docs
  • Loading branch information
oliver-oloughlin authored Mar 5, 2024
2 parents 8f6c6ae + e357df8 commit a0e59e1
Show file tree
Hide file tree
Showing 9 changed files with 295 additions and 66 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ _Supported Deno verisons:_ **^1.40.0**
- [flat()](#flat)
- [Extensions](#extensions)
- [Zod](#zod)
- [zodModel()](#zodmodel)
- [Kv-Schemas](#kv-schemas)
- [`zodModel()`](#zodmodel)
- [Schemas](#schemas)
- [Migrate](#migrate)
- [Script](#script)
- [Function](#function)
Expand Down Expand Up @@ -1241,7 +1241,7 @@ some dependenices to enhance integration. All extensions are found in the

### Zod

#### zodModel()
#### `zodModel()`

Provides additional compatibility when using zod schemas as models. While zod
schemas can be used as models directly, `zodModel()` properly parses a model
Expand Down Expand Up @@ -1275,10 +1275,10 @@ const result = await db.users_zod.add({
})
```

#### Kv-Schemas
#### Schemas

The zod extension provides schemas for some of the Kv-types, such as KvId,
KvValue, KvObject and Kvarray. This makes it easier to properly build your
KvValue, KvObject and KvArray. This makes it easier to properly build your
schemas.

```ts
Expand Down
1 change: 0 additions & 1 deletion deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
"bench": "deno bench --unstable-kv",
"prep": "deno task check && deno fmt && deno lint && deno publish --dry-run && deno task test"
},
"lock": false,
"fmt": {
"semiColons": false
},
Expand Down
53 changes: 53 additions & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 35 additions & 1 deletion ext/migrate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,38 @@
import { parseArgs } from "jsr:@std/[email protected]/parse_args"
/**
* @module # Migrate
*
* A utility script and function for migrating entries from a source KV instance to
* a target KV instance. Only migrates `kvdex` entries by default, but optionally
* allows for migrating all entries.
*
* ## Script
*
* Run the migrate script and provide --source and --target arguments. Optionally
* pass --all to migrate all entries.
*
* ```console
* deno run -A --unstable-kv jsr:@olli/kvdex/ext/migrate --source=./source.sqlite3 --target=./target.sqlite3
* ```
*
* ## Function
*
* Use the migrate function and pass a source KV instance and a target KV instance.
* Optionally pass `all: true` to migrate all entries.
*
* ```ts
* import { migrate } from "jsr:@olli/kvdex/ext/migrate"
*
* const source = await Deno.openKv("./source.sqlite3")
* const target = await Deno.openKv("./target.sqlite3")
*
* await migrate({
* source,
* target
* })
* ```
*/

import { parseArgs } from "jsr:@std/cli@^0.217/parse_args"
import { KVDEX_KEY_PREFIX } from "../src/constants.ts"

if (import.meta.main) {
Expand Down
63 changes: 62 additions & 1 deletion ext/zod.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,65 @@
import { z } from "npm:zod@3"
/**
* @module # Zod
*
* Extended support for Zod. Includes a model parser and schemas for some KV-types.
*
* ## `zodModel()`
*
* Provides additional compatibility when using zod schemas as models. While zod
* schemas can be used as models directly, `zodModel()` properly parses a model
* from a zod schema, recognizing default fields as optional.
*
* ```ts
* import { z } from "npm:zod"
* import { zodModel } from "jsr:@olli/kvdex/ext/zod"
* import { collection, kvdex } from "jsr:@olli/kvdex"
*
* const UserSchema = z.object({
* username: z.string(),
* gender: z.string().default("not given"),
* })
*
* const kv = await Deno.openKv()
*
* const db = kvdex(kv, {
* users_basic: collection(UserSchema),
* users_zod: collection(zodModel(UserSchema)),
* })
*
* // Produces a type error for missing "gender" field.
* const result = await db.users_basic.add({
* username: "oliver",
* })
*
* // No type error for missing "gender" field.
* const result = await db.users_zod.add({
* username: "oliver",
* })
* ```
*
* ## Schemas
*
* The zod extension provides schemas for some of the Kv-types, such as KvId,
* KvValue, KvObject and KvArray. This makes it easier to properly build your
* schemas.
*
* ```ts
* import { z } from "npm:zod"
* import { KvIdSchema } from "jsr:@olli/kvdex/ext/zod"
*
* const UserSchema = z.object({
* username: z.string(),
* postIds: z.array(KvIdSchema),
* })
*
* const PostSchema = z.object({
* text: z.string(),
* userId: KvIdSchema,
* })
* ```
*/

import { z } from "npm:zod@^3.22"
import type { KvArray, KvId, KvObject, KvValue, Model } from "../src/types.ts"

/*******************/
Expand Down
49 changes: 8 additions & 41 deletions src/collection.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type {
AtomicListOptions,
BuilderFn,
CheckKeyOf,
CollectionKeys,
Expand All @@ -8,7 +7,7 @@ import type {
EnqueueOptions,
FindManyOptions,
FindOptions,
HandleManyOptions,
HandleOneOptions,
HistoryEntry,
IdempotentListener,
IdGenerator,
Expand Down Expand Up @@ -36,6 +35,7 @@ import type {
SetOptions,
UpdateData,
UpdateManyOptions,
UpdateOneOptions,
UpdateOptions,
UpdateStrategy,
UpsertOptions,
Expand Down Expand Up @@ -568,39 +568,6 @@ export class Collection<
return await this.setDocument(id, data, options)
}

/**
* Write a document to the KV store.
*
* Sets a new document entry if no matching id already exists, overwrites the exisiting entry if it exists.
*
* Does not overwrite existing entries if there is a primary index collision.
*
* @deprecated
* This method is deprecated and will be removed in a future release.
*
* Please use `set()` with the option `overwrite: true` instead.
*
* @example
* ```ts
* const result = await db.users.write("anders", {
* username: "andy",
* age: 24
* })
* ```
*
* @param id - Document id.
* @param value - Document value.
* @param options - Set options, optional.
* @returns Promise resolving to a CommitResult or CommitError.
*/
async write(
id: KvId,
value: ParseInputType<TInput, TOutput>,
options?: SetOptions,
): Promise<CommitResult<TOutput> | Deno.KvCommitError> {
return await this.setDocument(id, value, { ...options, overwrite: true })
}

/**
* Deletes one or more documents with the given ids from the KV store.
*
Expand Down Expand Up @@ -1041,7 +1008,7 @@ export class Collection<
* @returns Promise resolving to either a commit result or commit error object.
*/
async updateOne<
const T extends UpdateManyOptions<Document<TOutput>>,
const T extends UpdateOneOptions<Document<TOutput>>,
>(
data: UpdateData<TOutput, T["strategy"]>,
options?: T,
Expand Down Expand Up @@ -1084,7 +1051,7 @@ export class Collection<
* @returns Promise resolving to either a commit result or commit error object.
*/
async updateOneBySecondaryIndex<
const T extends UpdateManyOptions<Document<TOutput>>,
const T extends UpdateOneOptions<Document<TOutput>>,
const K extends SecondaryIndexKeys<TOutput, TOptions>,
>(
index: K,
Expand Down Expand Up @@ -1193,7 +1160,7 @@ export class Collection<
* @returns A promise that resovles to an object containing the iterator cursor
*/
async deleteMany(
options?: AtomicListOptions<Document<TOutput>>,
options?: ListOptions<Document<TOutput>>,
): Promise<Pagination> {
// Perform quick delete if all documents are to be deleted
if (selectsAll(options)) {
Expand Down Expand Up @@ -1297,7 +1264,7 @@ export class Collection<
* @returns A promise that resovles to the retreived document
*/
async getOne(
options?: ListOptions<Document<TOutput>>,
options?: HandleOneOptions<Document<TOutput>>,
): Promise<Document<TOutput> | null> {
// Get result list with limit of one item
const { result } = await this.handleMany(
Expand Down Expand Up @@ -1339,7 +1306,7 @@ export class Collection<
>(
index: K,
value: CheckKeyOf<K, TOutput>,
options?: ListOptions<Document<TOutput>>,
options?: HandleOneOptions<Document<TOutput>>,
): Promise<Document<TOutput> | null> {
// Create prefix key
const prefixKey = createSecondaryIndexKeyPrefix(
Expand Down Expand Up @@ -2219,7 +2186,7 @@ export class Collection<
private async handleMany<const T>(
prefixKey: KvKey,
fn: (doc: Document<TOutput>) => T,
options: HandleManyOptions<Document<TOutput>> | undefined,
options: ListOptions<Document<TOutput>> | undefined,
) {
// Create list iterator with given options
const selector = createListSelector(prefixKey, options)
Expand Down
6 changes: 3 additions & 3 deletions src/deps.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export { brotliCompressSync, brotliDecompressSync, constants } from "node:zlib"
export { ulid } from "jsr:@std/[email protected]"
export { concat } from "jsr:@std/[email protected]/concat"
export { ulid } from "jsr:@std/ulid@^0.217"
export { concat } from "jsr:@std/bytes@^0.217/concat"
export {
deepMerge,
type DeepMergeOptions,
} from "jsr:@std/[email protected]/deep_merge"
} from "jsr:@std/collections@^0.217/deep_merge"
Loading

0 comments on commit a0e59e1

Please sign in to comment.