cloudflare / cloudflare/chanfana
When overwriting `getSchema()` how to get typesafe validated data?
- Dominant language
- TypeScript
- Stars
- 767
- Forks
- 70
- Avg merge
- 25m
- Merged PRs (30d)
- 4
Description
We have already discussed this in https://github.com/cloudflare/chanfana/issues/165 , but I think it's better to create a separate issue for this, as it is not related to the original issue.
When extending Chanfana [`OpenAPIRoute`](https://github.com/cloudflare/chanfana/blob/main/src/route.ts#L12) one can overwrite the default `getSchema()` or `getSchemaZod()` function to overwrite schema properties.
```
getSchema(): OpenAPIRouteSchema {
// Use this function to overwrite schema properties
return this.schema
}
```
For example:
```
export class PagingRoute extends OpenAPIRoute {
defaultPageSize = 10;
maxPageSize = 50;
getSchema(): OpenAPIRouteSchema {
// Deep copy
const schema = { ...super.getSchema() }
schema.request.query = schema.request.query.merge(z.object({
page: z.number().int().optional()
pageSize: z.number().int().max(this.maxPageSize).optional()
}))
}
async doSomethingWithPagingParams() {
const validatedData = await this.getValidatedData();
// validatedData does not know about its type, so page and pageSize are not recognized.
..
}
}
export class GetCustomers extends PagingRoute {
schema = {
request: {
query: z.object({
expand: z.string(),
}),
},
responses: {
'200': {
content: {
'application/json': {
schema: CustomersResponseSchema,
},
},
},
},
};
async handle(request: Request, ctx: Context) {
const data = await this.getValidatedData();
const expand = data.query.expand; // this works, and vscode uses types.
const page = data.query.page; // vscode does not recognize page/pageSize paramaters...
// is it possible to get typesafe validated data including the additional fields?
doSomethingWithPagingParams();
..
}
}
```
When modifying the schema like this, is it possible to get typesafe validated data in both the `handle` function and in the extended `PagingRoute` class?
Or is it not meant to be used like that @G4brym ?
Contributor guide
Research direction
Start with src/route.ts and inspect OpenAPIRoute.getSchema(), getSchemaZod(), and getValidatedData() to understand how schema types are inferred. Compare the PagingRoute and GetCustomers examples in this issue, then determine whether inherited schema extensions can preserve types in both handle() and the parent class. Done means a documented or implemented approach that provides typed page and pageSize fields.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- api
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100