Skip to content

Commit

Permalink
chore: Add docs (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
schpet authored Aug 11, 2024
1 parent 9a63d93 commit 9757a3a
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
1 change: 1 addition & 0 deletions CONVENTIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
- Avoid unsafe types like any
- Prefer checking for presence with 'val == null' instead of '!val'
- Use unique test identifiers
- Don't add comments
65 changes: 64 additions & 1 deletion README.markdown
Original file line number Diff line number Diff line change
@@ -1,3 +1,66 @@
# zod urlsearchparams

a work in progress
convert a zod object to a URLSearchParam and vice versa.

- minimal urls, scalars are readable and editable by humans
- vectors are encoded with base64
- allows gracefully falling back to defaults with `lenientParse`
- zero dependencies outside of zod

## install

```bash
npm i zod-urlsearchparams
pnpm i zod-urlsearchparams
yarn add zod-urlsearchparams
ni zod-urlsearchparams
```

## examples

note: the following examples use the ZodURLSearchParamSerializer class api, but `serialize`, `parse`, `shape`, `lenientParse` etc are exported on their own too.

### serializing

```ts
import assert from "node:assert"
import { z } from "zod"
import { ZodURLSearchParamSerializer } from "zod-urlsearchparams"

// setup your schema
const schema = z.object({ name: z.string(), age: z.number(), hobbies: z.array(z.string()) })

// setup the serializer
const serializer = new ZodURLSearchParamSerializer(schema)

// serialize some data to url params
const data = { name: "John Doe", age: 30, hobbies: ["reading", "cycling"] }
const params = serializer.serialize(data)

// see how it looks–
assert.strictEqual(params.toString(), "name=John+Doe&age=30&hobbies=reading&hobbies=cycling")
```

### parsing

```ts
// sometimes people will visit a url that doesn't conform
const invalidParams = new URLSearchParams("name=Jane+Doe&age=nope&hobbies=reading&hobbies=gardening")

// so we provide defaults to fall back to
const defaultData: z.infer<typeof schema> = {
name: "Default Name",
age: 25,
hobbies: ["default hobby"],
}

// parse it :4)
const lenientResult = serializer.lenientParse(invalidParams, defaultData)

// it'll drop the invalid field and use the default value
assert.deepStrictEqual(lenientResult, {
name: "Jane Doe",
age: 25, // uses default value because 'nope' can't be parsed as a number
hobbies: ["reading", "gardening"],
})
```

0 comments on commit 9757a3a

Please sign in to comment.