0.4.0 β€’ Published 1 year ago

@kiyoshiro/type-safe-path v0.4.0

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

type-safe-path

codecov npm version

Usage

npm i -D @kiyoshiro/type-safe-path
npx type-safe-path // generate a path helper file

Features

  • πŸƒ Tiny runtime code
  • πŸš€ Zero config (Currently supports Next, Nuxt3 and SvelteKit)
  • πŸ› οΈοΈ Configurable for adapt any frameworks

Abstract

pages/
  └── posts/
         β”œβ”€β”€index.svelte
         └──[id].svelte

↓ $ type-safe-path

type PathToParams = {
  "/posts": {
    query?: Record<string, string | number | string[] | number[]>
    hash?: string
  }
  "/posts/[id]": {
    params: { id: string | number }
    query?: Record<string, string | number | string[] | number[]>
    hash?: string
  }
}

/**
 * @example
 * $path('/posts/[id]', { params: { id: 1 }}) // => '/posts/1'
 */
export function $path<Path extends keyof PathToParams>(
  path: Path,
  args: PathToParams[Path]
): string {
  return (
    path.replace(/\[(\w+)\]/g, (_, key) => (args as any).params[key]) +
    (args.query
      ? "?" + new URLSearchParams(args.query as any).toString()
      : "") +
    (args.hash ? "#" + args.hash : "")
  )
}

/**
 * @example
 * $echoPath('/posts/[id]') // => '/posts/[id]'
 */
export function $echoPath<Path extends keyof PathToParams>(path: Path): string {
  return path
}

https://user-images.githubusercontent.com/40315079/224537579-e3a28043-68cd-4a0a-bcfc-73df8113456d.mp4

Comparison

This librarypathpida
API$path('posts/id', { params: { id: 1 }})pagesPath.posts._id(1).$url()
Bundle SizeConstant even if the number of paths increases, because it only generates few functions.Increases as paths increase, because it generates a big object.
For long path(e.g. /foo/bar/baz)Just select one completion and we can search path like fuzzyNeeds to push . key many times for pagesPath.foo.bar.baz.$url()
Supported FrameworksAny frameworks (thanks to its flexible configuration)Next.js, Nuxt.js
0.1.0

1 year ago

0.3.0

1 year ago

0.2.0

1 year ago

0.2.0-beta.1

1 year ago

0.2.0-beta.0

1 year ago

0.4.0

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago