Typesafe responses (RPC Mode) #4
Draft
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Adds a new object
rpc
that you use instead of the usualapi
, which automatically callsrequest.json()
for you, and types it automatically.How It Works & Limitations
The Vite plugin has been extended to also emit return type information to the
api.d.ts
file, like this:Obtaining the return type of the function is not trivial, as it always returns
Response
while we are actually interested in the data contained within. To solve this, I decided to tap into the most common pattern of making responses in SvelteKit - the built-injson
function. The plugin will search forreturn json(...)
and emit the type of whatever was passed intojson
, in a similar fashion to how the body type is scraped fromawait validate(...)
. If you don't usejson
, then the response is typed asany
(I would have usedunknown
but obtaining it with the TypeScript Compiler API is currently quite involved)Another limitation is only one
return
statement is supported. While I was able to get the types of allreturn json(...)
instances, I was not able to create a union type from them.Error Handling
I chose a simple and versatile behaviour: if the response code is anything other than 200, the RPC call will throw, and make the response object available.
Other Considerations
There is potentially another way to implement this without adding a new
rpc
object, which would be to hijack theResponse
object and provide type information toresponse.json()
. Though, doing it this way seems very hacky.Closes #3