Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for zod validation error callback in schema stream #80

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions public-packages/schemaStream/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,15 @@ class SchemaStream<T extends ZodObject<any>> {
parse(options?: {
stringBufferSize?: number;
handleUnescapedNewLines?: boolean;
onComplete: (data: {
isValid: boolean,;
errors: ZodError[];
data: data:
| {
[x: string]: any
}
| undefined
}) => void
}): TransformStream;
}
```
Expand Down Expand Up @@ -335,6 +344,7 @@ const parser = new SchemaStream(schema, {

- `stringBufferSize`: Size of the buffer for string values (default: 0)
- `handleUnescapedNewLines`: Handle unescaped newlines in JSON (default: true)
- onSchemaInvalid: Callback that will return any zod errors found during validation if provided schema is strict. (default: (err: ZodError) => {})

### Schema Stub Utility

Expand Down
28 changes: 27 additions & 1 deletion public-packages/schemaStream/src/utils/streaming-json-parser.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { lensPath, set, view } from "ramda"
import { z, ZodObject, ZodOptional, ZodRawShape, ZodTypeAny } from "zod"
import type { ZodIssue } from "zod"

import JSONParser from "./json-parser"
import { ParsedTokenInfo, StackElement, TokenParserMode, TokenParserState } from "./token-parser"
Expand Down Expand Up @@ -65,6 +66,7 @@ type OnKeyCompleteCallback = (data: OnKeyCompleteCallbackParams) => void | undef

export class SchemaStream {
private schemaInstance: NestedObject
private schemaType: SchemaType
private activePath: (string | number | undefined)[] = []
private completedPaths: (string | number | undefined)[][] = []
private onKeyComplete?: OnKeyCompleteCallback
Expand All @@ -84,6 +86,7 @@ export class SchemaStream {
) {
const { defaultData, onKeyComplete, typeDefaults } = opts

this.schemaType = schema
this.schemaInstance = this.createBlankObject(schema, defaultData, typeDefaults)
this.onKeyComplete = onKeyComplete
}
Expand Down Expand Up @@ -222,7 +225,20 @@ export class SchemaStream {
opts: {
stringBufferSize?: number
handleUnescapedNewLines?: boolean
} = { stringBufferSize: 0, handleUnescapedNewLines: true }
onComplete?: ({
isValid,
errors,
data
}: {
isValid: boolean
errors: ZodIssue[]
data:
| {
[x: string]: any
}
| undefined
}) => void
} = { stringBufferSize: 0, handleUnescapedNewLines: true, onComplete: () => null }
) {
const textEncoder = new TextEncoder()

Expand All @@ -233,6 +249,16 @@ export class SchemaStream {

parser.onToken = this.handleToken.bind(this)
parser.onValue = () => void 0
parser.onEnd = () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of passing a conditional callback that depends on another flag - would it be easier for us to just allow an onComplete here and just by default pass through the safeparse results always?

feels like making sure that isStrictSchmea is set on the instance AND havaing to pass the callback might be a bit confusing/unintuitive

vs say just adding

.parse({ onComplete })

and we conditional add the onEnd wiht a safeParse inside of it? We could also jsut pasas through the finala result and any other meta we have for free

  const stream = parser.parse({
    onComplete:({ isValid, errors = [], data }) => {
      errors = zodError.errors
    }
  })

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah I dig that, that way you can do whatever you want

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

love it, updated

const parsedResult = this.schemaType.safeParse(this.schemaInstance)

opts.onComplete &&
opts.onComplete({
isValid: parsedResult.success,
errors: parsedResult.error?.errors ?? [],
data: parsedResult.data
})
}

const stream = new TransformStream({
transform: async (chunk, controller): Promise<void> => {
Expand Down
27 changes: 25 additions & 2 deletions public-packages/schemaStream/tests/zod-types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { SchemaStream } from "@/utils/streaming-json-parser"
import { describe, expect, test } from "bun:test"
import { lensPath, view } from "ramda"
import { z, ZodObject, ZodRawShape } from "zod"
import type { ZodIssue } from "zod"

const checkPathValue = (obj: object, path: (string | number)[]) => {
const lens = lensPath(path)
Expand All @@ -13,14 +14,20 @@ const checkPathValue = (obj: object, path: (string | number)[]) => {

async function runTest<T extends ZodRawShape>(schema: ZodObject<T>, jsonData: object) {
let completed: (string | number)[][] = []
let errors: ZodIssue[] = []

const parser = new SchemaStream(schema, {
onKeyComplete({ completedPaths }) {
completed = completedPaths as (string | number)[][]
}
})

const stream = parser.parse()
const stream = parser.parse({
onComplete: ({ errors: validationErrors }) => {
errors = validationErrors
}
})

const decoder = new TextDecoder()
const encoder = new TextEncoder()

Expand Down Expand Up @@ -63,7 +70,7 @@ async function runTest<T extends ZodRawShape>(schema: ZodObject<T>, jsonData: ob
result = value
}

return { result: JSON.parse(decoder.decode(result)), completed }
return { result: JSON.parse(decoder.decode(result)), errors, completed }
}

describe("schema stream types", () => {
Expand Down Expand Up @@ -192,4 +199,20 @@ describe("schema stream types", () => {
expect(checkPathValue(data, path)).toBe(true)
})
})

test("zod with incorrect schema", async () => {
const schema = z
.object({
someString: z.string().default("test"),
someNumber: z.number().default(420)
})
.strict()

const data = {
cats: 48
}

const { errors } = await runTest(schema, data)
expect(errors).not.toBeEmpty()
})
})
Loading