@bitovi/querystring-parser

中文文档
0.8.1发布于 2023/12/14MITCommonJS近 30 天下载 4821
原始使用文档
文档目录11 节
  1. Why querystring-parser?
  2. Installation
  3. Usage
  4. Sort Parameters
  5. Pagination Parameters
  6. Include Parameters
  7. Fields Parameters
  8. Filter Parameters
  9. MongoDB-Style Filter Parameters
  10. IBM-Style Filter Parameters
  11. Development / Contributing

querystring-parser

Tests Workflow Status Join our Slack

Why querystring-parser?

Consider the following situation:

  • You're building a standard CRUD app that more-or-less follows the JSON:API specification
  • This app will receive HTTP GET requests with querystrings like those in the examples below:
    • ?filter[start_date][$gt]=2020-01-01
    • ?sort=-date,name&page[number]=1&page[size]=5
    • ?fields[articles]=title,body&fields[people]=name
  • You need to parse these query parameters to fetch the requested data. This library does the querystring parsing for you.

Installation

npm install @bitovi/querystring-parser

If you plan to use this library with Objection or Sequelize, do not install @bitovi/querystring-parser. Instead, install either:

Usage

const querystringParser = require("@bitovi/querystring-parser");

const { page } = querystringParser.parse("page[number]=1&page[size]=10");
console.log(page.number); // --> 1
console.log(page.size); // --> 10

Sort Parameters

The parsed results of the sort query parameters are stored in the sort property. The value of the sort property is an array of "sort field" objects. Each "sort field" object includes a field name and a sort direction.

Reference: JSON:API - Sorting

const { sort } = querystringParser.parse("sort=-date,name");
console.log(sort[0]); // --> { field: 'date', direction: 'DESC' }
console.log(sort[1]); // --> { field: 'name', direction: 'ASC' }

Pagination Parameters

The parsed results of the page query parameters are stored in the page property. The value of the page property is an object which has 2 keys: number and size.

Reference: JSON:API - Pagination

const { page } = querystringParser.parse("page[number]=1&page[size]=10");
console.log(page.number); // --> 1
console.log(page.size); // --> 10

Include Parameters

The parsed results of the include query parameter is stored in the include property. The value of the include property is an array of "relationship paths".

Reference: JSON:API - Inclusion of Related Resources

const { include } = querystringParser.parse("include=children.movies.actors.children,children.movies.actors.pets,children.pets,pets");
console.log(include[0]); // --> 'children.movies.actors.children'
console.log(include[1]); // --> 'children.movies.actors.pets'
console.log(include[2]); // --> 'children.pets'
console.log(include[3]); // --> 'pets'

Fields Parameters

The parsed results of the fields[TYPE] query parameters are stored in the fields property. The value of the fields property is an object. For each key-value pair in that object, the key is the name of a type and the value is an array of fields for that type.

Reference: JSON:API - Sparse Fieldsets

const { fields } = querystringParser.parse("fields[articles]=title,body&fields[people]=name");
console.log(fields.articles); // --> [ 'title', 'body' ]
console.log(fields.people); // --> [ 'name' ]

Filter Parameters

The parsed results of the filter query parameters are stored in the filter property. There are 2 "styles" of querystring filters that are supported. "MongoDB-Style" and "IBM-Style". Though they have their own conventions, they both produce the same kind of output. You can use both of these styles if you want, but not in the same querystring.


MongoDB-Style Filter Parameters

The MongoDB-Style is based off of the MongoDB comparison query operators.

Quick Examples

Querystring FilterParsed Output
filter[name]=brad{ LIKE: [ '#name', '%brad%' ] }
filter[name][$eq]=mike{ '=': [ '#name', 'mike' ] }
filter[age][$gt]=21{ '>': [ '#age', 21 ] }
filter[born][$lte]=2020-01-01{ '<=': [ '#born', '2020-01-01' ] }
filter[score][$eq]=%00{ 'IS NULL': '#score' }
filter[name][$in]=michael,brad{ IN: [ '#name', 'michael', 'brad' ] }

MongoDB-Style Operators

Below is the full list of MongoDB-Style operators and their compatible value types.

Operatorstringsnumbersdatesnullsarrays
$eq✅✅✅✅❌
$ne✅✅✅✅❌
$gt✅✅✅❌❌
$gte✅✅✅❌❌
$lt✅✅✅❌❌
$lte✅✅✅❌❌
ilike✅❌❌❌❌
$in✅✅✅✅✅
$nin✅✅✅✅✅

Omitted Operators

MongoDB-Style filters do not require explicit operators. In many cases, the value type is enough for the parser to infer which operator to use. The examples below demonstrate operator inference for each value type.

Value TypeExampleOutput
stringfilter[name]=lisa{ LIKE: [ '#name', '%lisa%' ] }
numberfilter[age]=25{ '=': [ '#age', 25 ] }
datefilter[born]=2020-01-01{ '=': [ '#born', '2020-01-01' ] }
nullfilter[score]=%00{ 'IS NULL': '#score' }
arrayfilter[name]=mike,brad{ IN: [ '#name', 'mike', 'brad' ] }

Arrays

The following examples demonstrate how array values may be specified.

  • Using repeating query params:
    • filter[age][$in]=24&filter[age][$in]=25&filter[age][$in]=26
  • Using commas (,):
    • filter[age][$in]=24,25,26

Both styles will result in the same output: { IN: [ '#age', 24, 25, 26 ] }

Compound Filters

MongoDB-Style filters do not directly support higher-order operators (AND / OR / NOT). However, if multiple filters are present in the query string then they will be joined together in an AND fashion.

// example of 2 filters getting "AND"-ed together into a compound filter
const { filter } = querystringParser.parse("filter[name]=mike&filter[age]=25");
expect(filter).toEqual({
  AND: [
    { LIKE: ["#name", "%mike%"] },
    { "=": ["#age", 25] }
  ]
});

IBM-Style Filter Parameters

The IBM-Style is based off of the jsonapi.net filtering specification.

Quick Examples

Querystring FilterParsed Output
filter=contains(name,'brad'){ LIKE: [ '#name', '%brad%' ] }
filter=equals(name,'mike'){ '=': [ '#name', 'mike' ] }
filter=greaterThan(age,'25'){ '>': [ '#age', 25 ] }
filter=lessOrEqual(born,'2020-01-01'){ '<=': [ '#born', '2020-01-01' ] }
filter=any(name,'brad','mike'){ IN: [ '#name', 'brad', 'mike' ] }
filter=equals(score,null){ 'IS NULL': '#score' }
filter=not(equals(age,'25')){ NOT: { "=": ["#age", 25] } }
filter=and(any(age,'10','20'),equals(name,'mike')){ AND: [{ IN: ["#age", 10, 20] }, { "=": ["#name", "mike"] }] }
filter=or(any(age,'10','20'),equals(name,'mike')){ OR: [{ IN: ["#age", 10, 20] }, { "=": ["#name", "mike"] }] }

IBM-Style Operators

Below is the full list of IBM-Style operators and their compatible value types.

Operatorstringsnumbersdatesattribute refsnullsnested operators
equals✅✅✅✅✅❌
greaterThan✅✅✅✅❌❌
greaterOrEqual✅✅✅✅❌❌
lessThan✅✅✅✅❌❌
lessOrEqual✅✅✅✅❌❌
contains✅❌❌❌❌❌
startsWith✅❌❌❌❌❌
endsWith✅❌❌❌❌❌
any✅✅✅❌✅❌
not❌❌❌❌❌✅
and❌❌❌❌❌✅
or❌❌❌❌❌✅

Attribute References

Some of the IBM-Style operators can directly compare 2 different attributes (or "columns"). In the example below, wins and losses are attribute references (as opposed to constant values like 'emily' or '22').

By convention, attribute references are prefixed with a '#' in the parsed output to distinguish them from constant values.

// example attribute references
const { filter } = querystringParser.parse("filter=greaterThan(wins,losses)");
expect(filter).toEqual({ ">": ["#wins", "#losses"] });

Compound Filters

IBM-Style filters directly support higher-order operators (AND / OR / NOT). On top of that, if multiple filters are present in the query string then they will be joined together in an OR fashion.

// example of 2 filters getting "OR"-ed together into a compound filter
const { filter } = querystringParser.parse("filter=contains(name,'mike')&filter=equals(age,'25')");
expect(filter).toEqual({
  OR: [
    { LIKE: ["#name", "%mike%"] },
    { "=": ["#age", 25] }
  ]
});

Development / Contributing

See CONTRIBUTING.md

版本与发布记录

@bitovi/querystring-parser 共发布 39 个版本,首次发布于 2022/05/14;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.8.1latest2023/12/142 年前
0.8.02023/12/082 年前
0.7.122023/12/052 年前
0.7.112023/12/052 年前
0.7.102023/12/052 年前
0.7.92023/12/052 年前

关于 @bitovi/querystring-parser 的常见问题

@bitovi/querystring-parser 是什么?

[](https://www.bitovi.com/community/slack?utm_source=badge

如何安装 @bitovi/querystring-parser?

在项目目录运行 npm install @bitovi/querystring-parser,或使用 pnpm add / yarn add / bun add。

@bitovi/querystring-parser 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/bitovi__querystring-parser 是否存在。

@bitovi/querystring-parser 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@bitovi/querystring-parser 可以商用吗?

@bitovi/querystring-parser 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@bitovi/querystring-parser 的下载量有多少?

根据 npm 官方下载统计,@bitovi/querystring-parser 在 2026/10/08 – 2026/11/06 这 30 天内被下载 4,821 次,日均约 161 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@bitovi/querystring-parser 还在维护吗?

最新版本 0.8.1 发布于 2023/12/14(2 年前);至今共发布 39 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/05/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。