getQueryString
Description
Converts a rules configuration object back into a FilterQuery query string.Usage
getQueryString(filter: {
rules?: ({
field: string | number,
type?: "number" | "text" | "date" | "tuple",
predicate?: "month" | "year",
filter?: string,
includes?: any[],
value?: any
} | {
rules?: any[]; // nested rules
glue?: "and" | "or",
})[];
glue?: "and" | "or";
} | {
field: string | number,
type?: "number" | "text" | "date" | "tuple",
predicate?: "month" | "year",
filter?: string,
includes?: any[],
value?: any
}): {
query: string;
warnings: string[];
}
Parameters
getQueryString takes a filter tree as input, which can be either a single filtering rule or a group of such rules, and returns an object containing the serialized query string and any warnings for rules that can't be expressed in query syntax.
Warnings are emitted for:
- Fields with type
"tuple"- no query syntax representation exists - Unknown
typevalues values
Details
Serialization notes:
predicate: "yearMonth"- stored asyear * 12 + month; serialized back toYYYY-MM.predicate: "year"with a 4-digit value - the.yearsuffix is omitted:start: 2024instead ofstart.year: 2024.predicate: "month"- always uses the explicit suffix:start.month: 6.- Values matching reserved words (
and,or,contains,starts,ends) or containing special characters are automatically quoted. field: nullorfield: undefinedwithincludesorvalue- serialized as tag syntax:#value.
Example
Serialize a multi-rule filter:
import { getQueryString } from "@svar-ui/react-filter";
const filter = {
glue: "and",
rules: [
{ field: "status", filter: "equal", value: "Open" },
{ field: "age", filter: "greater", value: 25 },
],
};
const { query, warnings } = getQueryString(filter);
// query: 'status: Open and age: >25'
// warnings: []
Nested groups:
const { query } = getQueryString({
glue: "and",
rules: [
{ field: "project", filter: "equal", value: "Alpha" },
{
glue: "or",
rules: [
{ field: "status", filter: "equal", value: "Open" },
{ field: "status", filter: "equal", value: "In Progress" },
],
},
],
});
// query: 'project: Alpha and (status: Open or status: "In Progress")'
Date predicate with yearMonth encoding:
const { query } = getQueryString({
field: "start",
predicate: "yearMonth",
value: 24294, // year*12+month encoding for 2024-06
});
// query: 'start: 2024-06'
Persist filter state as a URL parameter:
const { query } = getQueryString(filterValue);
const url = new URL(window.location.href);
url.searchParams.set("filter", query);
history.pushState({}, "", url);
Related articles: Query syntax