valibot icon indicating copy to clipboard operation
valibot copied to clipboard

feat: Add TransformStream Validation

Open BlackAsLight opened this issue 1 year ago • 1 comments

A TransformStream that validates each chunk of a stream asserting each chunk is of a provided schema.

I've found something like this would work.

import { BaseIssue, BaseSchema, InferOutput, parse } from "@valibot/valibot"

export class VStream<TSchema extends BaseSchema<unknown, unknown, BaseIssue<unknown>>>
	extends TransformStream<unknown, InferOutput<TSchema>> {
	constructor(schema: TSchema) {
		super({
			transform(chunk, controller) {
				controller.enqueue(parse(schema, chunk))
			},
		})
	}
}

Then it could be used like this.

const readable = ReadableStream.from(async function* () {
	for (let i = 0; i < 10; ++i)
		yield new Array(Math.ceil(Math.random() * 5)).fill(0).map(_ => Math.floor(Math.random() * 10))
}())
	.pipeThrough(new VStream(v.array(v.number())))

for await (const array of readable)
	console.log(array)

BlackAsLight avatar Aug 13 '24 11:08 BlackAsLight

This is out of scope for now, but maybe something we will look at again in the future.

fabian-hiller avatar Aug 15 '24 10:08 fabian-hiller