Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/dzucconi/queryparams
Parse and coerce query string. Set defaults and enforce a schema.
https://github.com/dzucconi/queryparams
querystring schema
Last synced: 10 days ago
JSON representation
Parse and coerce query string. Set defaults and enforce a schema.
- Host: GitHub
- URL: https://github.com/dzucconi/queryparams
- Owner: dzucconi
- License: mit
- Created: 2016-10-25T10:44:58.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2023-01-06T05:12:53.000Z (almost 2 years ago)
- Last Synced: 2024-10-12T15:06:28.073Z (24 days ago)
- Topics: querystring, schema
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/queryparams
- Size: 726 KB
- Stars: 2
- Watchers: 3
- Forks: 0
- Open Issues: 12
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# queryparams
## What is this?
A library to help you receive and update parameters in the querystring.
## Why should I use it?
- You want to limit the types of parameters you receive from the querystring.
- You need to set some default values and want any values coming from the querystring to be cast as the same type.
- You need a simple interface to reconfigure those values and redirect to a correctly updated querystring.## Installation
```bash
yarn add queryparams
# or
npm i queryparams --save
```## Usage
Assume we have a querystring with a value of:
```ts
"?speed=200&color=blue";
```## Set defaults and infer types
```ts
import { configure } from "queryparams";const { params } = configure({ visible: true, speed: 500, color: "red" });
// params: {
// visible: boolean;
// speed: number;
// color: string;
// }
```Values in the querystring override the default values and are coerced into matching types.
```ts
const { schema } = configure({
visible: true,
speed: 500,
color: "red",
});// schema => [
// { param: 'visible', default: true, type: 'boolean' },
// { param: 'speed', default: 500, type: 'number' },
// { param: 'color', default: 'red', type: 'string' }
]
```## Reconfiguring the querystring
```ts
const { reconfigure, encode } = configure({ message: "default", size: 9 });encode({ message: "next", size: 66 }); // => 'message=next&size=66'
encode({ message: "next", size: "notanumber" }); // => Uncaught Error: size should be a number
encode({ weird: true }); // => Uncaught Error: weird should be undefined// redirects to `?message=new&size=5`; enforces that types match defaults provided
reconfigure({ message: "new", size: 5 });
```