- 
          
- 
                Notifications
    You must be signed in to change notification settings 
- Fork 2.1k
feat: generated types for page and endpoint paths #9938
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
Conversation
| 🦋 Changeset detectedLatest commit: 3b79bcc The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
 Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR | 
| Update: rewritten the PR and made an update on the way the response types should be read. | 
c088a42    to
    3e06b2f      
    Compare
  
    | Any updates on this? | 
| In these past weeks i didn't have any spare time to continue this, however i plan to continue in the summer. | 
3e06b2f    to
    64adf9d      
    Compare
  
    b4e48f3    to
    ccc443f      
    Compare
  
    46b5486    to
    5c051c3      
    Compare
  
    | It took not long to complete what i said earlier, now i would like to see if the main contributors like this proposal, and to discuss it. The PR has been rewritten to accurately represent the new features (the changeset file is not representative yet, sorry!) | 
| i should add that this is not ready to be merged, but rather to decide whether to merge it in the future once completed or to leave it be. | 
      
        
              This comment was marked as outdated.
        
        
      
    
  This comment was marked as outdated.
| Any updates on this? | 
| Just a heads up: the merge conflict comes from  | 
| 
 I agree. I wouldn't expect type safety with a URL object. | 
| Yep URL objects are not typed. Since redirect was changed I did not edit the code but it would be a small fix to at least accept URL objects much like 'goto'. I'm honestly just waiting to see some feedback from the main contributors before putting in any more work into this PR | 
| @difanta What do you think about the approach I described in #647 (comment) ? We get typed URLs, along with typed responses and also ability to later extend it to support a typed request  I am considering creating a new PR that implements this | 
f5c1186    to
    01be9ee      
    Compare
  
    01be9ee    to
    7ab3e06      
    Compare
  
    | @difanta can you check out the approach I described in #11108, maybe we can collaborate on a proposal. I think there's a few issues with approaching the URL strings using template syntax (eg:  I think it makes a lot of sense to have a  eg: ....
namespace "$api" {
    export async function api_fetch(url: "/api/posts/[post]", options?: FetchOptions<ApiPostsPostParamParams, "GET">): Promise<TypedResponse<{ foo: string }>>;
}We'd then call this and provide the parameters for the URL via the options, eg: import { api_fetch } from "$api"
let res = await api_fetch("/api/posts/[post]", {
    method: "GET",
    params: {
        post: 123
    })
    
let json = await res.json() | 
| @AlbertMarashi Yeah yesterday I read your pr and comments and I like them a lot, I am trying a few things then I'll write my opinion, overall I think your wrapper could work better | 
| Great, looking forward to hearing feedback and collaborating. It would be really nice if TypeScript had microsoft/TypeScript#6579 supported but unfortunately doing the params in a templated string presents a lot of difficulties from my experimentation | 
7ab3e06    to
    8020163      
    Compare
  
    8020163    to
    8c406aa      
    Compare
  
    …tch type safety when fetching from endpoints
8c406aa    to
    3b79bcc      
    Compare
  
    | Closing this in favour of #11108 | 
Please don't delete this checklist! Before submitting the PR, please make sure you do the following:
Tests
pnpm testand lint the project withpnpm lintandpnpm checkChangesets
pnpm changesetand following the prompts. Changesets that add features should beminorand those that fix bugs should bepatch. Please prefix changeset messages withfeat:,fix:, orchore:.Description
I made a script to generate paths and types for endpoints, so that fetch calls can return a typed response both with fetch in a load function and global.fetch.
A
.svelte-kit/types/$api.d.tsfile is generated duringsyncthat contains path and type informations.I also extended this to ensure that
fetch,gotoandredirectpoint to a correct path, avoiding misspelling or errors when refactoring a site.This seems like a graceful addition to svelte kit to get end-to-end typing and i personally really enjoyed having this option in my projects.
This originated from discussions:
I've created a GitHub Project to share the tasks and information on this experiment SvelteKit Typed Endpoints and Paths.
I think enough work has been made to prove that this functionality works and could be a valid addition to Kit, now a discussion must be made to see if this is actually a thing that we want to merge or it's not exactly what we want. If this is accepted i will happily finish the remaining tasks.
I understand that tRPC seems like the obvious and more powerful solution here, but this is a zero-code addition that i think would benefit a lot of users, tRPC could still be added by those who feel like this is not enough.
New Features:
Path matching:
to get all these functions to actually check the path passed to them an argument with type different from
stringmust be passed, for example:Fetch("/api/foo")is good because the argument type is "/api/foo"Fetch("/api" + "/foo")orlet path = '/api/foo'; Fetch(path)are not good as the argument type isstring, these are allowed but will not be checked for misspelling and will not have type on the responseimport { base } from "$app/paths";to match exactly that path (no longer a unspecified '' | `${string}`),so Fetch(`${base}/api/foo`) works both if the path was or wasn't set
Fetch types:
Currently fetch types work with a specific endpoint syntax, with the
export const GET = async function () { ... } satisfies RequestHandlerconstraint and not the defaultexport const GET: RequestHandler = () { ... }where it seems impossible to know the return type of the path.This should be easily fixed with a proxy rewrite of +server.js/ts files like it is done with load functions, just a heads up.
The type returned from a Fetch call is TypedResponse<T> | TypedResponse<App.Error>, and checking for response.ok discriminates between the two. This was my choice and i think it promotes good code, although i do not know if all 'not ok' response actually return an App.Error object.
Fetch typed response