1.0.7 • Published 2 years ago
fastest-custom-validators v1.0.7
fastest-custom-validators
Created by Ignacio Loyola
ignacio.loyola@youorder.me
Setup in moleculer.js
or equivalent:
/**
* Base moleculer configuration
* If possible, override depending on the environment
*/
import config from './environment.js';
import validator from 'fastest-custom-validators';
// Base or default moleculer config
const base = { // this is the base config file for the ServiceBroker
// .
// .
// .
validator: validator, // put the validator here.
Objects exposed:
ObjectIdValidator(throwable Error class)
: Validates for validObjectId
ofmongo
.ObjectIdArrayValidator(throwable Error class)
: Validates for array ofObjectId
.dateValidator(throwable Error class)
: Validates formongo
-compatible date object.validator
: Custom fastest-validator validator object.disjunctionValidator(throwable Error class, arrayOfFilters: [(value) => bool], errorType: string, expected: string)
: Generator for a validator that is truthy if any filter passestrue
.
Validator usage
Example in MoleculerJs service
// ...
import {ObjectIdValidator, dateValidator, ObjectIdArrayValidator} from 'fastest-custom-validators';
/**
* Announcement service
*/
export default class AnnouncementService extends Service {
// .
// .
// ...
actions: {
show: {
params: {
// Validate for Object Id, passing the corresponding error. The standard 'Error' could also be passed
id: ObjectIdValidator(ValidationFailureError),
$$strict: true,
},
handler: this.show,
},
create: {
params: {
// additional options can be passed, just like any other validation.
customerId: {...ObjectIdValidator(ValidationFailureError), optional: true},
description: {type: 'string'},
title: {type: 'string'},
enabled: {type: 'boolean', default: true},
isPublic: {type: 'boolean', default: true},
isPermanent: {type: 'boolean', default: false},
visibleToSegments: {...ObjectIdArrayValidator(ValidationFailureError), default: []},
initDate: dateValidator(ValidationFailureError),
endDate: dateValidator(ValidationFailureError),
placesToShow: {type: 'array', items: 'string', default: ['home']},