An open API service indexing awesome lists of open source software.

https://github.com/jill64/svelte-qparam

🔎 Type-Safe Query Parameter for SvelteKit
https://github.com/jill64/svelte-qparam

library querystring svelte sveltekit typesafe

Last synced: 7 months ago
JSON representation

🔎 Type-Safe Query Parameter for SvelteKit

Awesome Lists containing this project

README

          

# svelte-qparam

npm-version npm-license npm-download-month npm-min-size ci.yml website

🔎 Type-Safe Query Parameter for SvelteKit

## [Demo](https://svelte-qparam.jill64.dev)

## Installation

```sh
npm i svelte-qparam
```

## Bulk Parameters

Use the `define` function to set multiple parameter definitions at once.

```svelte

import { page } from '$app/state'
import { define } from 'svelte-qparam'
import { string, number, boolean } from 'svelte-qparam/serde'

const extract = define({
str: string,
num: number,
bool: boolean
})

// https://example.com/?str=value&num=123&bool=false
let { values, qparams: q } = $derived(extract(page.url))

// {
// str: 'value',
// num: 123,
// bool: false
// }
console.log(values)

// output 'value'
console.log(q.str)
q.num = 456
q.bool = true

```

### Fullstack Type-Safety

Values defined with the `define` function can be used in `+page.js` and `+page.server.js`.
This allows you to handle parameters type-safely across applications across servers and clients.

```js
// +page.js
import { define } from 'svelte-qparam'
import { string, number, boolean } from 'svelte-qparam/serde'

export const _extract = define({
str: string,
num: number,
bool: boolean
})

export const load = ({ url, data }) => {
const { values, qparams } = _extract(url)

// ...

return {
qparams
}
}
```

```js
// +page.server.js
import { _extract } from './+page.js'

export const load = ({ url }) => {
const { values } = _extract(url)

// ...

return {
// Note: Cannot return `qparams` from server
// ...
}
}
```

```svelte

let { data } = $props()

let { qparams: q } = $derived(data)

// ...

```

## License

[MIT](LICENSE)