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

joi-async

v0.0.7

Published

# DO NOT USE YET!

Downloads

3

Readme

joi-async

DO NOT USE YET!

Async validation support for Joi. Adds mixins to Joi object to allow custom async validation callbacks.

Usage

import 'joi-async'
import Joi from 'joi';
// or you can use
// import Joi from 'joi-async';
// ... or via require()
// require('joi-async');
// const Joi = require('joi');

const checkUsernameIsUnique = (value, state, options) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // same error message keys as in Joi
      value === 'taken' ? reject('!!The username "{{!value}}" has already been taken') : resolve();
    }, 500);
  });
};

(async () => {
  const schema = Joi.object().keys({
      username: Joi.string().alphanum().required().async(checkUsernameIsUnique),
      password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),
      email: Joi.string().email({ minDomainAtoms: 2 })
  });
  
  try {
    const filteredValues = await schema.asyncValidate({ 
        username: 'taken', 
        password: '123456',
        email: '[email protected]',
    });    
  } catch (e) {
    console.log(e.details);
    /*
    [
      {
        "message": "The username \"taken\" has already been taken",
        "path": [
          "username"
        ],
        "type": "customAsync.error",
        "context": {
          "value": "taken",
          "key": "username",
          "label": "username"
        }
      }
    ]
    */
  }
})();

Methods

any.async(callback)

  • callback - callback function can be synchronous or Promise-based

Joi.asyncValidate(value, schema, [options], [callback])

Same rules as Joi.validate() but with extra options

any.validate(value, [options], [callback])

Same rules as any.validate() but with extra options

Options

  • afterSyncSuccess: defaults to true. All callbacks will be called only after regular synchronous flow is successful.

Callbacks

Callbacks can return Promise or be synchronous. A callback receives the following arguments:

  • value - the value being processed by Joi.
  • state - an object containing the current context of validation.
    • key - the key of the current value.
    • path - the full path of the current value.
    • parent - the potential parent of the current value.
  • options - options object provided through any().options() or Joi.validate().

If callback returns a value it will transform original value in the output in case if { convert: true } is used.

Errors

You can use Promise.reject('error template') or throw 'error template'. However, if you need full control over resulting error details you can use JoiAsyncError to override errorCode as well

JoiAsyncError(message[, errorCode])

  • message - error message template, same rules as regular Joi error messages. (e.g. !!Example error message label: {{label}}, value: {{!value}})
  • errorCode - defaults to customAsync.error
import JoiAsyncError from 'joi-async/error';
import Joi from 'joi';

const checkUsernameIsUnique = (value) => {
  throw new JoiAsyncError('!!taken', 'error.taken');
};

(async () => {
  const schema = Joi.object().keys({
      username: Joi.string().required().async(checkUsernameIsUnique),
  });
  
  try {
    await schema.asyncValidate({ 
        username: 'taken', 
    });    
  } catch (e) {
    console.log(e.details);
    /*
    [
      {
        "message": "taken",
        "path": [
          "username"
        ],
        "type": "error.taken", // new code
        "context": {
          "value": "taken",
          "key": "username",
          "label": "username"
        }
      }
    ]
    */
  }
})();

Examples

Async with overriding

import 'joi-async'
import Joi from 'joi';

const removeBadWords = async (value) => {
  const withoutBadWords = await thirdPartyServiceToRemoveBadWords(value);
  
  // Will replace original value if {convert: true} option
  return withoutBadWords;
};

(async () => {
  const schema = Joi.object().keys({
      title: Joi.string().required().async(removeBadWords),
  });
  
  try {
    const filteredValues = await schema.asyncValidate({ 
        username: 'example', 
    });    
  } catch (e) {
      // standard Joi error object
  }
})();

Full example

import 'joi-async'
import Joi from 'joi';

const checkUsername = async (value) => {
  const available = await checkDatabaseUsernameAvailbale(value);
  
  if (!available) {
      throw '!!This username has already been taken';
  }
  
  // No need to return anything if you don't want to override it
};

(async () => {
  const schema = Joi.object().keys({
      title: Joi.string().required().async(checkUsername),
  });
  
  try {
    const filteredValues = await schema.asyncValidate({ 
        username: 'example', 
    });    
  } catch (e) {
      // standard Joi error object
  }
})();

Synchronous example

import 'joi-async'
import Joi from 'joi';
import _ from 'lodash';

const kebabify = (value) => {
  // works only with { convert: true }
  return _.kebabCase(value);
};

(async () => {
  const schema = Joi.object().keys({
      title: Joi.string().required().async(kebabify),
  });
  
  try {
    const filteredValues = await schema.asyncValidate({ 
        key: 'Example Message', 
    });
    
    console.log(filteredValues.key); // example-message
  } catch (e) {
      // standard Joi error object
  }
})();