Kikobeats/to-query · 文件 下载 ZIP
文件最后提交记录最后更新时间
README.md
以下内容由 AI 翻译,如有问题请点此提交 issue 反馈
从请求 URL 作为输入获取查询对象。
亮点
- 获取任意 URL 的查询参数。
例如/?foo=bar→{ foo: 'bar' } - 将键名规范化为驼峰命名法。
例如/?user_agent=googlebot→{ userAgent: 'googlebot' } - 自动将值转换为原生类型。
例如/?plan_id=123→{ planId: 123 } - 友好的布尔值。
例如/?is_enabled→{ isEnabled: true } - 声明默认值。
例如/?→{ accept: '*' }
它还支持必填字段、验证、错误处理等功能。
安装
$ npm install to-query --save
快速入门
to-query 是一种便捷的方式,可从任意请求 URL 作为输入获取查询参数。
const toQuery = require('to-query')()
const query = toQuery('/?foo=bar') // => { foo: 'bar' }
默认值
有时,你需要关联一个默认值,以便在未提供值时使用:
const userAgentString = require('ua-string')
const createQuery = require('to-query')
const toQuery = createQuery({
userAgent: {
default: userAgentString
}
})
toQuery('/?') // => { userAgent: 'Mozilla/5.0 (Macintosh; Intel…' }
toQuery('/?user_agent=googlebot') // => { userAgent: 'googlebot' }
必需
将字段声明为必需意味着在字段缺失时会抛出错误:
const createQuery = require('to-query')
const toQuery = createQuery({
url: {
required: true
}
})
toQuery('/?foo=bar')
// => TypeError: Expected `string` for `url`, got `undefined`
自定义错误消息
如果你提供的是 string 而不是 boolean,它将被用作显示在错误下方的消息:
const createQuery = require('to-query')
const toQuery = createQuery({
url: {
required: 'You need to provide an URL.'
}
})
toQuery('/?foo=bar')
// => TypeError: You need to provide an URL.
Validate
如果你需要对预期值中值的形状进行细粒度的类型检查,你可以声明任意类型的验证,从而轻松与其他包进行集成:
const isUrlHttp = require('is-url-http')
const createQuery = require('to-query')
const toQuery = createQuery({
url: {
validate: {
validator: isUrlHttp,
message: input => `The value '${input}' is not a valid http(s) URL.`
}
}
})
toQuery('/?url=kikobeats.com')
// => TypeError: The value 'kikobeats.com' is not a valid http(s) URL.
Transform
你可以使用一个或多个函数来修改单个值,以生成最终输出:
const createQuery = require('to-query')
const split = str => str.split(',').map(item => item.trim())
const toQuery = createQuery({
url: {
filters: {
transform: [split]
}
}
})
toQuery('/?filters=prerender,auto,resize')
// => { filters: ['prerender', 'auto', 'resize'] }
用法
to-query 的设计目标是只做好一件事。
在这方面,to-query 是框架无关的,让你可以自由地将其与软件的其他部分集成。
如果你想在任何 HTTP 服务器(Express、Micro、Koa、Hapi、Fastify 等)中使用它,只需提供请求的 url 即可。
const toQuery = require('to-query')()
module.exports = (req, res) => {
req.query = createQuery(req.url)
res.end('Your query is', req.query)
}
就是这样!
API
toQuery = to-query([options])
它会创建 to-query 实例。
options
提供的任何选项都会传递给 osom,请查阅 文档 以了解更多信息。
此外,你可以设置
map
类型:function
一个在 处理 URL 之前作为映射器运行的函数。
默认的 map 仅将键转换为驼峰命名法。
toQuery(input)
必填
类型: string|object
要转换为查询对象的输入值。
许可证
to-query © Kiko Beats, 根据 MIT 许可证发布。
由 Kiko Beats 编写和维护,并得到 contributors 的帮助。
kikobeats.com · GitHub Kiko Beats · Twitter @Kikobeats