Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
serialize-query-params
Advanced tools
A library for simplifying encoding and decoding URL query parameters.
The serialize-query-params npm package is a utility for serializing and deserializing URL query parameters in JavaScript. It provides a simple and consistent way to handle query parameters, making it easier to work with URLs in web applications.
Serialize Query Parameters
This feature allows you to convert an object of query parameters into a query string. The `stringify` function takes an object and returns a URL-encoded string.
const { stringify } = require('serialize-query-params');
const queryParams = { name: 'John', age: 30 };
const queryString = stringify(queryParams);
console.log(queryString); // Output: 'name=John&age=30'
Deserialize Query Parameters
This feature allows you to convert a query string back into an object. The `parse` function takes a URL-encoded string and returns an object representing the query parameters.
const { parse } = require('serialize-query-params');
const queryString = 'name=John&age=30';
const queryParams = parse(queryString);
console.log(queryParams); // Output: { name: 'John', age: 30 }
Custom Parameter Serialization
This feature allows you to customize the serialization of query parameters. For example, you can specify how arrays should be formatted in the query string.
const { stringify } = require('serialize-query-params');
const queryParams = { name: 'John', age: 30, tags: ['developer', 'blogger'] };
const queryString = stringify(queryParams, { arrayFormat: 'comma' });
console.log(queryString); // Output: 'name=John&age=30&tags=developer,blogger'
The `qs` package is a query string parser and stringifier with support for nested objects, arrays, and other advanced features. It is more feature-rich compared to serialize-query-params, offering more customization options for parsing and stringifying query parameters.
The `query-string` package provides methods for parsing and stringifying URL query strings. It is similar to serialize-query-params but offers additional features like sorting keys and handling arrays and nested objects more gracefully.
The `url-search-params` package is a polyfill for the URLSearchParams API, which provides methods to work with the query string of a URL. It is a more modern approach and is built into modern browsers, making it a good alternative for environments that support it.
A library for simplifying encoding and decoding URL query parameters.
Used in React with use-query-params.
Using npm:
$ npm install --save serialize-query-params
For convenience, serialize-query-params exports parse
, stringify
, extract
, and parseUrl
functions from the query-string library.
See all param definitions here. You can define your own parameter types by creating an object with an encode
and a decode
function. See the existing definitions for examples.
Note that all nully values will encode and decode as undefined
.
Examples in this table assume query parameter named qp
.
Param | Type | Example Decoded | Example Encoded |
---|---|---|---|
StringParam | string | 'foo' | ?qp=foo |
NumberParam | number | 123 | ?qp=123 |
ObjectParam | { key: string } | { foo: 'bar', baz: 'zzz' } | ?qp=foo-bar_baz-zzz |
ArrayParam | string[] | ['a','b','c'] | ?qp=a&qp=b&qp=c |
JsonParam | any | { foo: 'bar' } | ?qp=%7B%22foo%22%3A%22bar%22%7D |
DateParam | Date | Date(2019, 2, 1) | ?qp=2019-03-01 |
DateTimeParam | Date | Date(2019, 2, 1) | ?qp=2019-02-28T22:00:00.000Z |
BooleanParam | boolean | true | ?qp=1 |
NumericObjectParam | { key: number } | { foo: 1, bar: 2 } | ?qp=foo-1_bar-2 |
DelimitedArrayParam | string[] | ['a','b','c'] | ?qp=a_b_c' |
DelimitedNumericArrayParam | number[] | [1, 2, 3] | ?qp=1_2_3' |
Example with Custom Param
You can define your own params if the ones shipped with this package don't work for you. There are included serialization 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 */
const CommaArrayParam = {
encode: (array: string[] | null | undefined): string | undefined =>
encodeDelimitedArray(array, ','),
decode: (arrayStr: string | string[] | null | undefined): string[] | undefined =>
decodeDelimitedArray(arrayStr, ',')
};
decodeQueryParams<QPCMap extends QueryParamConfigMap>(
paramConfigMap: QPCMap,
encodedQuery: Partial<EncodedValueMap<QPCMap>>
): Partial<DecodedValueMap<QPCMap>>
Convert the values in query from strings to their natural types via the decode functions configured in paramConfigMap.
Example
import {
stringify,
decodeQueryParams,
NumberParam,
} from 'serialize-query-params';
// encode each parameter according to the configuration
const decodedQuery = decodeQueryParams(
{ foo: NumberParam, bar: DelimitedArrayParam },
{ foo: '123', bar: 'a_b' }
);
// produces: { foo: 123, bar: ['a', 'b'] }
encodeQueryParams<QPCMap extends QueryParamConfigMap>(
paramConfigMap: QPCMap,
query: Partial<DecodedValueMap<QPCMap>>
): Partial<EncodedValueMap<QPCMap>>
Convert the values in query to strings via the encode functions configured in paramConfigMap. This can be useful for constructing links using decoded query parameters.
Example
import {
stringify,
encodeQueryParams,
NumberParam,
} from 'serialize-query-params';
// encode each parameter according to the configuration
const encodedQuery = encodeQueryParams(
{ foo: NumberParam, bar: DelimitedArrayParam },
{ foo: 123, bar: ['a', 'b'] }
);
// produces: { foo: '123', bar: 'a_b' }
const link = `/?${stringify(encodedQuery)}`;
export function updateLocation(
encodedQuery: EncodedQueryWithNulls,
location: Location
): Location {
Updates a location object to have a new query string (the search
field) based
on the encoded query parameters passed in via encodedQuery
. Parameters not
specified in encodedQuery
will be dropped from the URL.
Example
import { updateLocation } from 'serialize-query-params';
// location has search: ?foo=123&bar=abc
const newLocation = updateLocation({ foo: '555' }, location);
// newLocation has search: ?foo=555
// note that unspecified query parameters (bar in this case) are not retained.
export function updateInLocation(
encodedQueryReplacements: EncodedQueryWithNulls,
location: Location
): Location {
Updates a location object to have a new query string (the search
field) based
on the encoded query parameters passed in via encodedQueryReplacements
. Only
parameters specified in encodedQueryReplacements
are affected by this update,
all other parameters are retained.
Example
import { updateInLocation } from 'serialize-query-params';
// location has search: ?foo=123&bar=abc
const newLocation = updateLocation({ foo: '555' }, location);
// newLocation has search: ?foo=555&bar=abc
// note that unspecified query parameters (bar in this case) are retained.
Run the typescript compiler in watch mode:
npm run dev
FAQs
A library for simplifying encoding and decoding URL query parameters.
We found that serialize-query-params demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.