Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
This repository was archived by the owner on May 1, 2021. It is now read-only.

A javascript library for simplifying encoding and decoding URL query parameters

NotificationsYou must be signed in to change notification settings

pbeshai/serialize-query-params

Repository files navigation


Old README

serialize-query-params

A library for simplifying encoding and decoding URL query parameters.

npmTravis (.com)


Installation |API |useQueryParams


Used in React withuse-query-params.

Installation

Using npm:

$ npm install --save serialize-query-params query-string

Note: There is a peer dependency onquery-string. For IE11 support, use v5.1.1, otherwise use v6.

API

Param Types

Seeall param definitions here. You can define your own parameter types by creating an object with anencode and adecode function. See the existing definitions for examples.

Note that all null and empty values are typically treated as follows:

valueencoding
null?foo
""?foo=
undefined? (removed from URL)

Examples in this table assume query parameter namedqp.

ParamTypeExample DecodedExample Encoded
StringParamstring'foo'?qp=foo
NumberParamnumber123?qp=123
ObjectParam{ key: string }{ foo: 'bar', baz: 'zzz' }?qp=foo-bar_baz-zzz
ArrayParamstring[]['a','b','c']?qp=a&qp=b&qp=c
JsonParamany{ foo: 'bar' }?qp=%7B%22foo%22%3A%22bar%22%7D
DateParamDateDate(2019, 2, 1)?qp=2019-03-01
DateTimeParamDateDate(2019, 2, 1)?qp=2019-02-28T22:00:00.000Z
BooleanParambooleantrue?qp=1
NumericObjectParam{ key: number }{ foo: 1, bar: 2 }?qp=foo-1_bar-2
DelimitedArrayParamstring[]['a','b','c']?qp=a_b_c'
DelimitedNumericArrayParamnumber[][1, 2, 3]?qp=1_2_3'

Enum Param

You can define enum param usingcreateEnumParam. It works asStringParam but restricts decoded output to a list of allowed strings:

import{createEnumParam}from'serialize-query-params';// values other than 'asc' or 'desc' will be decoded as undefinedconstSortOrderEnumParam=createEnumParam(['asc','desc'])

Setting a default value

If you'd like to have a default value, you can wrap your param withwithDefault():

import{withDefault,ArrayParam}from'serialize-query-params';// by default, nulls are converted to defaultsconstNeverNullArrayParam=withDefault(ArrayParam,[]);// if you don't want nulls to be included, pass false as a third argconstNeverUndefinedArrayParam=withDefault(ArrayParam,[],false);

Example with Custom Param

You can define your own params if the ones shipped with this package don't work for you. There are includedserialization utility functions to make this easier, but you can use whatever you like.

import{encodeDelimitedArray,decodeDelimitedArray}from'serialize-query-params';/** Uses a comma to delimit entries. e.g. ['a', 'b'] => qp?=a,b */constCommaArrayParam={encode:(array:string[]|null|undefined):string|undefined=>encodeDelimitedArray(array,','),decode:(arrayStr:string|string[]|null|undefined):string[]|undefined=>decodeDelimitedArray(arrayStr,',')};

decodeQueryParams

decodeQueryParams<QPCMapextendsQueryParamConfigMap>(paramConfigMap:QPCMap,encodedQuery:Partial<EncodedValueMap<QPCMap>>):Partial<DecodedValueMap<QPCMap>>

Convert the values in query from strings to their natural types via thedecode functions configured in paramConfigMap.

Example

import{stringify,decodeQueryParams,NumberParam,DelimitedArrayParam}from'serialize-query-params';// encode each parameter according to the configurationconstdecodedQuery=decodeQueryParams({foo:NumberParam,bar:DelimitedArrayParam},{foo:'123',bar:'a_b'});// produces: { foo: 123, bar: ['a', 'b'] }

encodeQueryParams

encodeQueryParams<QPCMapextendsQueryParamConfigMap>(paramConfigMap:QPCMap,query:Partial<DecodedValueMap<QPCMap>>):Partial<EncodedValueMap<QPCMap>>

Convert the values in query to strings via the encode functions configuredin paramConfigMap. This can be useful for constructing links using decodedquery parameters.

Example

import{encodeQueryParams,DelimitedArrayParam,NumberParam,}from'serialize-query-params';import{stringify}from'query-string';// encode each parameter according to the configurationconstencodedQuery=encodeQueryParams({foo:NumberParam,bar:DelimitedArrayParam},{foo:123,bar:['a','b']});// produces: { foo: '123', bar: 'a_b' }constlink=`/?${stringify(encodedQuery)}`;

updateLocation

exportfunctionupdateLocation(encodedQuery:EncodedQuery,location:Location):Location{

Updates a location object to have a new query string (thesearch field) basedon the encoded query parameters passed in viaencodedQuery. Parameters notspecified inencodedQuery will be dropped from the URL.

Example

import{updateLocation}from'serialize-query-params';// location has search: ?foo=123&bar=abcconstnewLocation=updateLocation({foo:'555'},location);// newLocation has search: ?foo=555// note that unspecified query parameters (bar in this case) are not retained.

updateInLocation

exportfunctionupdateInLocation(encodedQueryReplacements:EncodedQuery,location:Location):Location{

Updates a location object to have a new query string (thesearch field) basedon the encoded query parameters passed in viaencodedQueryReplacements. Onlyparameters specified inencodedQueryReplacements are affected by this update,all other parameters are retained.

Example

import{updateInLocation}from'serialize-query-params';// location has search: ?foo=123&bar=abcconstnewLocation=updateLocation({foo:'555'},location);// newLocation has search: ?foo=555&bar=abc// note that unspecified query parameters (bar in this case) are retained.

Development

Run the typescript compiler in watch mode:

npm run dev

[8]ページ先頭

©2009-2025 Movatter.jp