simple-params
TypeScript icon, indicating that this package has built-in type declarations

0.4.2 • Public • Published

Simple Params

Simple, tiny, and typed parameter parser.

Built to configure a parser for URLSearchParams and adapt to Prisma Client Query, Firestore Query, etc., with ease.

URLURLSearchParams → API Config → Simple Query Object

Download

npm install simple-params

Usage

import { parseNumber, simpleParams } from 'simple-params';

const api = simpleParams({
	size: (val) => 'I will always be this value',
	string: (val) => (val ? 'true' : 'false'),
	boolean: (val) => (val ? true : false),
	page_size: (val) => parseNumber(val, { fallback: 1, min: 1, max: 100 }),
});

const params = api.parse(urlSearchParams);

Simply provide the simpleParams function with parameter keys and validator functions.

Get All

If you want to use getAll() to receive all the values associated with a given search parameter as an array, you can pass a second parameter to simpleParams.

import { parseNumber, simpleParams } from 'simple-params';

const api = simpleParams(
	{
		page_size: (val) => parseNumber(val, { fallback: 1, min: 1, max: 100 }),
	},
	{
		color: (val) => (val.length ? val : ['red']),
	}
);

const params = api.parse(urlSearchParams);

Parsers

parseNumber

import { parseNumber, simpleParams } from 'simple-params';

const api = simpleParams({
	page_size: (val) => parseNumber(val, { fallback: 1, min: 1, max: 100 }),
});

parseDate

import { parseDate, simpleParams } from 'simple-params';

const api = simpleParams({
	startDate: (val) => parseDate(val, { fallback: new Date() }),
});

Adapters

Next.js API Routes

import type { NextApiRequest, NextApiResponse } from 'next';
import { nextAdapter, parseNumber, simpleParams } from 'simple-params';

const api = simpleParams({
	page_size: (val) => parseNumber(val, { fallback: 1, min: 1, max: 100 }),
});

export default async function handler(
	req: NextApiRequest,
	res: NextApiResponse<any>
) {
	const params = api.parse(nextAdapter(req.query));
}

Package Sidebar

Install

npm i simple-params

Weekly Downloads

21

Version

0.4.2

License

ISC

Unpacked Size

8.74 kB

Total Files

13

Last publish

Collaborators

  • lukasmurdock