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

Custom request body validation #97

Open
henrytoone opened this issue Sep 11, 2023 · 2 comments
Open

Custom request body validation #97

henrytoone opened this issue Sep 11, 2023 · 2 comments

Comments

@henrytoone
Copy link
Contributor

henrytoone commented Sep 11, 2023

Is there a way to make use of the zod Schema.strict in the automatic validation of a request body? Or override/disable the automatic validation?

At the moment if I create a schema

const TestSchema = z.object({
    foo: z.string()
})


class TestPost extends OpenAPIRoute {
    static schema = {
        requestBody: TestSchema,
    }
    ...
}

And then send this payload to the route

{
    "foo": "example",
    "bar": "example"
}

this will be accepted as valid even though "bar" is not a valid property on TestSchema
TestSchema.strict(...) is how I would handle this manually but unsure how/if the default validation behaviour would be modified. Or is the only way to handle this to parse the data again in the handler?

@G4brym
Copy link
Member

G4brym commented Sep 11, 2023

Hey @henrytoone to enable the strict mode, you just need to enable the raiseUnknownParameters flag in the router.
Check the router options here.

@henrytoone
Copy link
Contributor Author

Hi @G4brym , I gave this a go and it doesn't seem to be working. I'm not sure if it's something else I've missed but the option seems to have no effect

const router = OpenAPIRouter({
	raiseUnknownParameters: true,
});

const TestSchema = z.object({
	foo: z.string(),
});

class TestPost extends OpenAPIRoute {
	static schema = {
		requestBody: TestSchema,
	};
	async handle(request: Request, env: any, context: any, data: Record<string, any>) {
		// Create typed object
		const body = TestSchema.parse(data.body);

		return { ok: true };
	}
}

router
	.post('/test', TestPost)

	// 404 for all misses
	.all('*', () => error(404, 'not found'));

Then sending the payload below still returns the ok response

{
    "foo": "example",
    "bar": "example"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants