n-params-processor
v6.0.0
Published
Node.js parameters parser/validator mongodb/sequelize filter builder
Downloads
15
Maintainers
Readme
n-params-processor
Node.js parameters parser/validator and mongodb/sequelize query/data-object builder.
Installation
$ npm i n-params-processor
Example of usage
const MongooseQB = require('n-params-processor').MongooseQB
const DataBuilder = require('n-params-processor').DataBuilder
/* Request:
- GET /api/users?role=user&fields=firstName%20lastName&users[]=1,2,3&page=5&count=10&sortBy=firstName
*/
exports.getUsers = async (req, res, next) => {
try {
const ALLOWED_FIELDS = 'id firstName lastName age'
const DEFAULT_FIELDS = 'id firstName lastName'
let queryBuilder = new MongooseQB({
source: req.query
})
queryBuilder.parseString({ name: 'role', az: 'userRole', required: true })
queryBuilder.parseArray({ name: 'users', az: 'userId', itemType: 'int', op: 'in' })
queryBuilder.parseFields({ allowed: ALLOWED_FIELDS, def: DEFAULT_FIELDS })
queryBuilder.parsePagination()
queryBuilder.parseSorting()
let query = queryBuilder.build()
/* query is an object: {
filter: {
userRole: { $eq: 'user' },
userId: { $in: [1, 2, 3] }
},
fields: 'firstName lastName',
pagination: { page: 5, count: 10 },
sorting: { sortBy: 'firstName', sortDirection: 'asc' }
}*/
let users = await usersSrvc.getUsers(query)
res.send(users)
} catch (err) {
next(err)
}
}
/* Request:
- POST /api/users
BODY: {
firstName: 'John',
age: '25',
roles: ['user']
}
*/
exports.createUser = async (req, res, next) => {
try {
let dataBuilder = new DataBuilder({
source: req.body,
data: { creator: req.user.userId }
})
dataBuilder.parseString({ name: 'firstName', max: 10, required: true })
dataBuilder.parseString({ name: 'lastName', max: 20, def: 'not prodived' })
dataBuilder.parseInt({ name: 'age', min: 18, max: 55, required: true })
dataBuilder.parseArray({ name: 'roles', allowed: ['user', 'admin', 'owner'], itemType: 'string' })
let userData = dataBuilder.build()
/* userData is an object: {
creator: '58ea5b07973ab04f88def3fa', // base value
firstName: 'John',
lastName: 'not prodived', // default value is used
age: 25, // age converted to Number
roles: ['user']
}*/
let user = await usersSrvc.createUser(userData)
res.send(user)
} catch (err) {
next(err)
}
}
API
consts
The constants objects. OPERATORS
field contains all valid query operators.
ParamsProcessorError
The error object that package throws in the case of error.
DataBuilder
See DataBuilder.
MongooseQB
See QueryBuilder.
SequelizeQB
See QueryBuilder.
BaseBuilder API
- This is a base builder class, an object of this class shouldn't be used directly. Instead of this inherit of
QueryBuilder
orDataBuilder
must be used.
constructor(params)
params
is an object with the following fields:source
: base source object, can bereq.body
for example. Parsers will use this source if custom is not provided, optional.data
: base data object, can include some common fields:{ currentUser: req.user }
for example, optional.
parseType(params)
Common parameters of parseType
method.
params
is an object with the following fields:source
: source object, if not providedinstance.source
is used, optional.name
: parameter name.az
: new name, optional.def
: default value, is used when parameter value is nil, optional.required
: indicates that parameter value is mandatory, optional.to
: object that should be used to save parsed value, optional.
parseString(params)
Parses, converts to String
and validates parameter value.
params
is an object with the same fields as for parseType, except:min
: the lowest possible string length, optional.max
: the largest possible string length, optional.allowed
: validates thatallowed
array includes parameter value, optional.
parseDate(params, output)
Parses, converts to Date
and validates parameter value.
params
is an object with the same fields as for parseType, except:format
: is date time format, if not providedmonent.defaultFormat
is used, optional.formatRes
: is a result object format, can beDate
or format string, optional.min
: the lowest possible date, optional.max
: the largest possible date, optional.
parseJson(params)
Parses, converts to JSON
and validates parameter value.
params
is an object with the same fields as for parseType.
parseBool(params)
Parses, converts to Boolean
and validates parameter value.
params
is an object with the same fields as for parseType.
parseNumber(params)
Parses, converts to Number
and validates parameter value.
params
is an object with the same fields as for parseType, except:min
: the lowest possible value, optional.max
: the largest possible value, optional.allowed
: validates thatallowed
array includes parameter value, optional.
parseInt(params)
Parses, converts to IntegerNumber
and validates parameter.
params
is an object with the same fields as for parseNumber.
parseFloat(params)
Parses, converts to FloatNumber
and validates parameter.
params
is an object with the same fields as for parseNumber.
parseRegexp(params)
Parses and validates parameter.
params
is an object with the same fields as for parseType, except:pattern
: Regular expression that should be used to test parameter value.
parseObjectId(params)
Parses, converts to ObjectId
and validates parameter.
params
is an object with the same fields as for parseType.
parseEmail(params)
Parses and validates email parameter.
params
is an object with the same fields as for parseType.
parseCustom(params)
Parses and validates parameters using custom handler.
params
is an object with the same fields as for parseType, except:handler
: the function that accepts value and returns some result, required.
parseArray(params)
Parses, converts to itemType
and validates parameter.
params
is an object with the same fields as for parseType, except:itemType
the array item type (on of the registered parser types:Int
,String
,Bool
, etc).itemHandler
the handler for custom item type.allowed
: validates that parameter value is subset ofallowed
array, optional.
DataBuilder API
Should be used for creating a plain data object, to use in create and update operations.
constructor(params)
params
is an object with the same fields as for BaseBuilder.constructor.
build()
Returns a final data object.
QueryBuilder (MongooseQueryBuilder, SequelizeQueryBuilder) API
Should be used for generating database query.
constructor(params)
params
is an object with the same fields as for BaseBuilder.constructor, except:filter
: base filter, can include some common parameters, optional.
parseFields(params)
Parses, converts and validates fields parameter. Validated parameter value must be space separated string of values.
params
is an object with the following fields:source
: source object, if not definedinstance.source
is used.fieldsName
: the name offields
parameter, if not providedfields
is used, optional.allowed
: space separated string of allowed fields.def
: space separated string of default fields.
parsePagination(params)
Parses, converts and validates pagination parameters. By default pagination object is null.
params
is an object with the following fields:source
: source object, if not definedinstance.source
is used.pageName
: the name ofpage
parameter, if not providedpage
is used, optional.countName
: the name ofcount
parameter, if not providedcount
is used, optional.
parseSorting(params)
Parses, converts and validates sorting parameters. By default sorting object is null.
params
is an object with the following fields:source
: source object, if not definedinstance.source
is used.sortByName
: the name ofsortBy
parameter, if not providedsortBy
is used, optional.sortDirName
: the name ofsortDirection
parameter, if not providedsortDirection
is used, optional.
build()
Returns a final query with filter
, fields
, pagination
and sorting
fields.
Author
Alexander Mac
License
Licensed under the MIT license.