Skip to content

Commit

Permalink
chore: Better examples
Browse files Browse the repository at this point in the history
  • Loading branch information
schpet committed Aug 14, 2024
1 parent ae4afe2 commit 7b6ce1e
Showing 1 changed file with 95 additions and 42 deletions.
137 changes: 95 additions & 42 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ convert a zod object to a URLSearchParam and vice versa.
- allows gracefully falling back to defaults with `lenientParse`
- zero dependencies outside of zod

[introductory blog post](https://schpet.com/note/building-a-typescript-library-with-aider) explaining how this library was built with [aider](https://aider.chat/).

## install

```bash
Expand All @@ -16,51 +18,102 @@ 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
## usage

```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")
import { z } from "zod";
import { lenientParse, parse, serialize } from "zod-urlsearchparams";

let schema = z.object({
age: z.bigint(),
species: z.enum(["dog", "cat"]),
interests: z.array(z.string()),
location: z.object({
room: z.string(),
}),
});

let serialized = serialize({
schema,
data: {
age: BigInt(5),
species: "dog",
interests: ["sleeping", "sniffing"],
location: {
room: "kitchen",
},
},
});
console.log(serialized.toString());
// age=5&species=dog&interests=sleeping&interests=sniffing&location=eyJyb29tIjoia2l0Y2hlbiJ9

let strictParsed = parse({
schema,
input: new URLSearchParams(
"age=10&species=cat&interests=sleeping&interests=sniffing&location=eyJyb29tIjoiY2F0aW8ifQ"
),
});
console.log(strictParsed);
// {
// age: 10n,
// species: 'cat',
// interests: [ 'sleeping', 'sniffing' ],
// location: { room: 'catio' }
// }

let lenientParsed = lenientParse({
schema,
input: new URLSearchParams("age=10&species=cat"),
defaultData: {
age: BigInt(0),
species: "dog",
interests: [],
location: { room: "kitchen" },
},
});
console.log(lenientParsed);
// {
// age: 10n,
// species: 'cat',
// interests: [],
// location: { room: 'kitchen' }
// }
```

### parsing
### class based api

```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"],
})
```
import { ZodURLSearchParamSerializer } from "zod-urlsearchparams";
let serializer = new ZodURLSearchParamSerializer(schema);
let serializedBySerializer = serializer.serialize({
age: BigInt(5),
species: "dog",
interests: ["sleeping", "sniffing"],
location: {
room: "kitchen",
},
});
console.log(serializedBySerializer.toString());
// age=5&species=dog&interests=sleeping&interests=sniffing&location=eyJyb29tIjoia2l0Y2hlbiJ9
let parsedBySerializer = serializer.lenientParse(
new URLSearchParams(
"age=10&species=cat&interests=sleeping&interests=sniffing&location=eyJyb29tIjoiY2F0aW8ifQ"
),
{
age: BigInt(0),
species: "dog",
interests: [],
location: { room: "kitchen" },
}
);
console.log(parsedBySerializer);
// {
// age: 10n,
// species: 'cat',
// interests: [ 'sleeping', 'sniffing' ],
// location: { room: 'catio' }
// }
```

0 comments on commit 7b6ce1e

Please sign in to comment.