cloudflare / chanfana

OpenAPI 3 and 3.1 schema generator and validator for Hono, itty-router and more!
https://chanfana.pages.dev
MIT License
273 stars 36 forks source link

Custom request body validation #97

Open henrytoone opened 10 months ago

henrytoone commented 10 months ago

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 commented 10 months ago

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

henrytoone commented 10 months ago

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"
}