0.1.0 • Published 7 years ago
@bloxite/koa-query-defaults v0.1.0
Koa query defaults
Simple parsing and filtering of input params for Koa@2
Installation
npm install @bloxite/koa-query-defaults --save
This module made for work with koa-router.
Usage
const { query, body, params } = require('@bloxite/koa-query-defaults')
// or in ES6-way
import { query, body, params } from '@bloxite/koa-query-defaults'
Create middleware
To create middleware call one of these methods: query
, body
or params
. These method works with ctx.query
, ctx.body
or ctx.params
respectively and accept same rules. For example:
import { query } from '@bloxite/koa-query-defaults'
router.get(
'/posts',
query({
// parse `page` param as number in range from 1 to 50
// also this value is required
page: [ 'number', 'range:1..50' ],
// parse `tags` param as array
tags: [ 'array' ],
// parse `search` as string with length from 1 to 100
search: [ 'string', 'length:1..100' ],
// parse `sort` param as enum with possible values 'asc' and 'desc'
sort: [ 'values:asc,desc' ]
}),
(ctx) => {
const { query } = ctx
// GET /posts?page=2&tags=foo,bar&tags=baz&sort=desc
assert.strictEqual(query.page, 2)
assert.strictEqual(query.sort, 'desc')
assert.strictEqual(query.search, '')
assert.deepEqual (query.tags, [ 'foo', 'bar', 'baz' ])
}
)
Any runtime validation/parsing errors will be thrown as BadRequest
error from http-errors
package.
List of rules
Rules will apply in order of definition: [ 'number', 'value:1,2' ]
will not work, because first value will be converted to number and then will be matched against list of strings '1'
and '2'
.
Here is a list of rules:
default:<value>
— put<default>
value if input is not present;boolean
— parse"true"
,"on"
,"yes"
,"y"
,"1"
astrue
,"false"
,"off"
,"no"
,"n"
,"0"
asfalse
;number
— parse any input number to JS-number, also support hex, octal and binary numbers (e.g.GET /posts?page=0xDEADBEEF
);string
— return value as is if present (or coma-separated list of values if array is present), or empty string if value is not provided;array:<separator>
— split input parameter by optional<separator>
(default is,
) and returns array (empty array for empty input);required
— return an errors if no parameter is present;length:<min>..<max>
— validate string length, where<min>
is lower bound and<max>
is upper bound;range:<min>..<max>
— same aslength
but valdate number value;enum:<val1>,<val2>,...
— check value (or every value in array) to match a list of allowed values;values
(deprecated) — same asenum
;
Known issues
router.use(query(/* ... */))
has no effect;