-
Notifications
You must be signed in to change notification settings - Fork 14
Open
Description
Bug report
I'm trying to use the library for JSON streaming + schema validation.
I tried to stream this JSON string { "foobar": "foobar" }
with this Zod schema:
const schema = z.object({
someString: z.string(),
someNumber: z.number(),
})
I don't get any error from the parser but since the Zod schema is not respected, I should get one
Is it the normal behavior?
Full working example:
import { SchemaStream } from 'schema-stream'
import { z } from 'zod'
const schema = z.object({
someString: z.string(),
someNumber: z.number(),
})
async function getSomeStreamOfJson(
jsonString: string
): Promise<{ body: ReadableStream }> {
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder()
const jsonBytes = encoder.encode(jsonString)
for (let i = 0; i < jsonBytes.length; ) {
const chunkSize = Math.floor(Math.random() * 5) + 2
const chunk = jsonBytes.slice(i, i + chunkSize)
controller.enqueue(chunk)
i += chunkSize
}
controller.close()
},
})
return { body: stream }
}
async function main() {
const response = await getSomeStreamOfJson(`{"foobar": "foobar"}`)
let result = {}
const parser = new SchemaStream(schema)
const streamParser = parser.parse({})
response.body?.pipeThrough(streamParser)
const reader = streamParser.readable.getReader()
const decoder = new TextDecoder()
while (true) {
const { value, done } = await reader.read()
if (done) {
console.log('Final result: ', result)
break
}
const chunkValue = decoder.decode(value)
result = JSON.parse(chunkValue)
}
}
main()
Metadata
Metadata
Assignees
Labels
No labels