Open theetrain opened 3 months ago
Another idea is to adopt Open API Schema or something similar to what Hono does; allow the developer to define response schemas manually to parse out any unwanted data: https://hono.dev/examples/zod-openapi
Perhaps instead of solving this first-party, maybe SvelteKit can expose a way to allow third-party validators (Zod, AJV, Valibot, VineJS) to plug into SvelteKit types to achieve the following opt-in behaviours:
load
, form actions, or endpoint responses are missing a schema.handle
) to parse responses and impact generated types returned to the data
and form
props.fetch
to autocomplete endpoints, REST verbs, and response types; relates to #647.
Updated 2024 November 9 to include other proposals from below comments.
Describe the problem
My team is provided a set of internally-managed API client libraries. We use
+page.server.js
to make API requests withinload
and return data to the page.It's easy to make the mistake of returning the full API response to the page without filtering out potentially sensitive fields.
Describe the proposed solution
1. Type overrides
Some way to override generated types through a global declarations file. I would imagine that would be a tough challenge since something like
PageServerLoad
is generated based on its inferred return type on a per-route basis; so I'm unsure of a conventional declarations file could work versus a JS function received bysvelte.config.js
.Hypothetically, this override would allow me to centrally configure unacceptable return types such as the following:
And that way, it would give pause to the developer to ensure they have sanitized their response:
2. New
schema
reserved exportIn
+page.server.js
, allow developers to export avalidate
function that is called afterload
and before data gets server-rendered or returned to the client.validate
export. Such assvelte.config.js@kit.validateAllRoutes:true
, which helps developers remember to add avalidate
export to any server file with aload
or endpoint export+page.server.js
+server.js
This example needs more thought.
Response
object?400/409/etc
responses3. Schema hooks
Relates to: https://github.com/sveltejs/kit/issues/12623 Inspired by: https://github.com/ahmadnassri/node-oas-fastify
And can potentially be its own ticket or enhancement.
Maybe developers could write a Vite plugin to parse their own schema methodology, such as OpenAPI Schema. The plugin needs a way to parse built SvelteKit routes in order to add custom middleware to them.
Given this file structure:
The schema
update.yml
contains data that maps to a path in the file-based router. In this case,update.yml
has keys that point to a SvelteKit endpoint as well as JSON schemas for validation based on response:Alternatives considered
load
method data in a validator before callingreturn
load
responses; similar to https://www.npmjs.com/package/oas-fastifyImportance
nice to have
Additional Information