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

Auto Generated +server.ts types for API calling #11101

Closed
Tracked by #11108
AlbertMarashi opened this issue Nov 22, 2023 · 1 comment
Closed
Tracked by #11108

Auto Generated +server.ts types for API calling #11101

AlbertMarashi opened this issue Nov 22, 2023 · 1 comment

Comments

@AlbertMarashi
Copy link

Something which kinda really sucks with creating APIs using SvelteKit +server.ts routes is that all the requests using fetch are untyped, as a result we don't receive typing on the front end, and have to manually constrain types

This can create a lot of surface area for bugs, as there can be a mismatch between the +server.ts and the fetch

My ideas are to somehow get SvelteKit to auto generate these types for use in the frontend

/api/hello/+server.ts

import { APIResponse, json } from "@svelte/kit"
export async function GET():  APIResponse<{ hello: "world" }>{
   return json({
      hello: "world" // these types are typechecked against the function response type to ensure correct data
   })
}

svelte code

export function json<T>(json: T): APIResponse<T> {
   // ...
}

/+page.ts

import { api_fetch } from "@svelte/kit" // a new tool exported by sveltekit that contains autogenerated types for all of the `+server.ts` routes
export async function load() {
   return {
        some_data: await api_fetch("GET", "/api/hello") // returns typed data
   }
   // the return type would look like { some_data: { hello: "world" } }
}

We could imagine that api_fetch looks like this using typescript function overloading with auto generated types

async function api_fetch(method: "GET", "/api/hello"): APIResponse<{ hello: "world" }>;
async function api_fetch(method: "GET", "/api/foo"): APIResponse<{ foo: "bar" }>;
async function api_fetch(method: Methods, url: string): APIResponse<any> {
   // ...
}

I think a lot of this should be possible with some typescript magic similar to how we're already doing with the load functions & page data

  1. How should parameterized routes work

Originally posted by @AlbertMarashi in #11042

@AlbertMarashi AlbertMarashi changed the title Auto Generated +server.ts types for API calling Auto Generated +server.ts types for API calling Nov 22, 2023
@eltigerchino
Copy link
Member

Closed as duplicate of #647

@eltigerchino eltigerchino closed this as not planned Won't fix, can't repro, duplicate, stale Nov 22, 2023
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