oedotme / generouted

Generated file-based routes for Vite
https://stackblitz.com/github.com/oedotme/generouted/tree/main/explorer
MIT License
1.02k stars 47 forks source link

fix: add types for splat params #127

Closed d0whc3r closed 11 months ago

d0whc3r commented 11 months ago

Following the example, router.ts file will be like this:

export type Path =
  | `/`
  | `/about`
  | `/posts`
  | `/posts/:id`
  | `/posts/:id/:pid?`
  | `/posts/:id/deep`
  | `/splat/${string}`

export type Params = {
  '/posts/:id': { id: string }
  '/posts/:id/:pid?': { id: string; pid?: string }
  '/posts/:id/deep': { id: string }
  '/splat/*': { '*': string }
}

adding '/splat/*': { '*': string } because "useParams" in a splat file will return an object with one key

export default function SplatAll() {
  const path = useParams('/splat/*')
  return <h1>All - {JSON.stringify(path)}</h1>
}

http://.../splat/asdf/a/d/b/e

path === { "*" : "asdf/a/d/b/e" }
oedotme commented 11 months ago

Hey @d0whc3r, thanks for submitting the PR.

I tested it out and found an issue — if there's a splat with another param it causes type keys duplication:

export type Path =
  | `/`
  | `/about`
  | `/posts`
  | `/posts/:id`
  | `/posts/:id/:pid?`
  | `/posts/:id/deep/*` // ←

export type Params = {
  '/posts/:id': { id: string }
  '/posts/:id/:pid?': { id: string; pid?: string }
  '/posts/:id/deep': { id: string } // ←
  '/posts/:id/deep': { '*': string } // ←
}

Mostly we'd need to add both params and splats to the same key in the previous condition:

if (param.length) {
  params.push(`'/${path}': { ${param.map((p) => p.replace(/:(.+)(\?)?/, '$1$2:') + ' string').join('; ')} }`)
}

Please let me know if you'd like to give it a try.

Thanks!

d0whc3r commented 11 months ago

@oedotme fixed 😄

oedotme commented 11 months ago

Hey @d0whc3r, I've pushed a small change to improve readability and to remove unnecessary splat condition. In addition, the Path type needed to be updated as well — as each Params key should match a Path.

Thanks again, I'll be releasing this shortly.

oedotme commented 11 months ago

Released in v1.16.0