npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

wallter

v0.0.11

Published

Wallter is an express and restify middleware validator that uses validator.js and has the ability to build validation schema straight from your mongoose model. It can dig up to the deepest defined array and/or array of objects and validate the data.

Downloads

4

Readme

wallter

Wallter is an express and restify middleware validator that uses validator.js and has the ability to build validation schema straight from your mongoose model. It can dig up to the deepest defined array and/or array of objects and validate the data.

It is highly influenced by ctavan/express-validator and relying from chriso/validator.js, wallter does almost the same goal as validator. The edge is, it supports auto validation for arrays, nested arrays, and/or nested arrays of objects without using customValidator workaround.

Installation

npm install --save wallter

Usage

Sample Mongoose Model

require('./model')()
const restify = require('restify')
const mongoose = require('mongoose')

const halter = require('wallter').halter
const Builder = require('wallter').builder

const server = restify.createServer({ name: 'myapp', version: '1.0.0'});

const builder = new Builder({
  uuid: true,
  model: mongoose.model('TestModel'),
  templates: {
    unique: `Expecting unique value in '%1$s' field. (Model: %2$s, Field: %3$s)`
  }
})

server.use(restify.plugins.acceptParser(server.acceptable))
server.use(restify.plugins.queryParser())
server.use(restify.plugins.bodyParser())

server.use(halter({
  customValidators: {
    // sample custom validator, supporting mongoose 'unique')
    unique: (value, modelName, field) => {
      return new Promise((resolve, reject) => {
        return setTimeout(() => {
          resolve()
        }, 500)
      })
    }
  }
}))

server.post('/test', function (req, res, next) {
  let validationSchema = builder
    .location('body')
    .exclude(['arr.*.foo'])
    .addRule('email', 'unique', ['modelName', 'email']) // custom validator above
    .build()

  req.halt(validationSchema).then(result => {
    if (result.length) {
      res.send(400, result)
    } else {
      res.send(200)
    }
    
    return next()
  })
})

server.listen(8080, function () {
  console.log('%s listening at %s', server.name, server.url);
})

Validator

All validator specified in validator.js v9.2.0 are attached and its validator name will be used as the rule name in validation schema.

Builder

Options

Option | Description ------------- | ------------------- uuid | Force to add validation isUUID() to fields _id and ref. Default: false uuidVersion | Version to use once uuid is enabled. Default: 5 model | Mongoose object model to parse to generate validation schema. templates | Error message templates object for your custom validator (see section below for Error Messages).

Validation Schema Generator/Builder (Mongoose specific)

The messy problems arrives if you have multiple REST resource and you need to write validation schema in each resource, or clever way is to reuse some of them if possible. But still it is messy. So why not use a validation schema generator from a defined mongoose model?

const Builder = require('wallter').builder

const builder = new Builder({
  uuid: true,
  model: mongoose.model('TestModel'),
  templates: {
    unique: `Expecting unique value in '%1$s' field. (Model: %2$s, Field: %3$s)`
  }
})

let schema = builder.build()
console.log(schema)

Sample Mongoose Schema Sample Validation Schema - Output

Validation Schema Manipulator

See basic tests for an in depth usage and samples.

Methods | Description ----------------------------------------------- | -------------------------------------- addRule(path, rule, options) | Add validation rule to existing validation item or create a new validation itemparams: - path {string} - path to property to validate- rule {string} - validation name, it can be from validator.js or your custom validator- options {array} - ordered params to pass to validator, successive array items can be used to print values in error message addRules([[path, rule, options]]) | Multilple addRule()param: rules {array} - array of addRule() params build() | Generate schema. cherryPick(options) | Set multiple location and select the defined items only (aka: pickByLoc()). param: options {object} - {location: [fieldPath, ...], ...}e.g. {query: ['_id'], body: ['foo.bar', 'arr.*.foo.bar']} dropRule(path, rules) | Remove validation rule from schema itemparams: - path {string} - path to property to validate - rules {string|string[]} - validation rule names to remove exclude(paths) | Remove specific field from pre generated schema (if mongoose model were attached)param: paths {(string|string[])} - path to property to validate fresh() | Produce an empty schema (ignoring mongoose model) select(paths) | Get specific field from pre generated schema (if mongoose model were attached)param: paths {(string|string[])} - path to property to validate* **setLocation(*loc*)** | Adds specific location (in each property to validate, or to the selected ones) on where to pull the data. *currently supported locations are 'params', 'query', 'body'*<br><br>***param:*** *loc {string} - possible values are: params\|query\|body* **setLocations(*options*)** | Multiple location setting. <br><br>***param:*** *options {object} - {location: [fieldPath, ...], ...}*<br>e.g. {query: ['_id'], body: ['foo.bar', 'arr..foo.bar']}` setOptional(path) | Set field to validate as optionalparam: path {string} - path to property to validate setRequired(path) | Set field to validate as requiredparam: path {string} - path to property to validate unstrict(arrPath) | Setting array of objects as optional even if object property inside is requiredparam: arrPath {(string|string[])} - path to property

Error Messages

By default, error messages to some validators are templated (see it here), but you can specify your own message by passing your error message template to our builder options.

It uses sprintf.js (vsprintf specifically) as an underlying mechanism to pass values to error messages/templates.

let options = {
  uuid: true,
  model: mongoose.model('BasicModel'),
  templates: {
    unique: `Expecting unique value in '%1$s' field.`,
    yourValidator: `Your message here, you can pass param values using sprintf.js syntax`
  }
}

Printing param values

In addRule() the 3rd array param options handles all values that you want to attach to your error message, but there is a numbering scheme. By default, I attached the path as the first item of the options array, the 2nd and succeeding will be the options to be passed to validator options if needed. Check sprintf.js or these tests for an in depth usage.

License

MIT License