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

format-schema

v3.0.0

Published

object input validation and sanitization

Downloads

27

Readme

format-schema Build Status

Object input validation and sanitization for node.js written in typescript

Installation

npm install --save-exact format-schema

API

const {
    format,
    promiseFormat,
    stringFormat,
    integerFormat,
    floatFormat,
    booleanFormat
} = require('format-schema')

Single value test

// Define test before executing format test, this will ensure test configuration validity.
// After initialization, format test can be reused.

const stringTest = stringFormat({capitalize: 'words'})

// Lazy example (don't use it in production envoirement)
// const result = stringFormat({capitalize: 'words'})('edgars')

module.exports = string => {
    const result = stringTest('edgars')

    if (result instanceof Error) {
        return new Error(result)
    }

    // Edgars
    return result
}

Schema value test

// Define test before executing format test, this will ensure tests configuration validity.
// After initialization, format test can be reused.

const formatTest = format({
    name: stringFormat({capitalize: 'words', min: 2, max: 20, trim: true, notEmpty: true}),
    age: integerFormat({min: 18, max: 99, notEmpty: true}),
    friends: [integerFormat({naturalNumber: true, notZero: true})]
})

// input
// {
//  name: ' edgars ',
//  age: 19,
//  friends: [10, 11, 12]
// }

module.exports = inputs => {
    const result = formatTest(inputs)

    if (result instanceof) {
        return new Error(result)
    }

    // output, valid and formatted
    // {
    //  name: 'Edgars',
    //  age: 19,
    //  friends: [10, 11, 12]
    // }
    return result
}

Error handling

// Format test will return result object or error object, use "instanceof Error"

const result = formatTest(inputs)

if (result instanceof Error) {
    // handle error here
}

Promise value test

// note: format runs synchronously, it is a wrapper function
const formatTest = promiseFormat({
    name: stringFormat({capitalize: 'words', min: 2, max: 20, trim: true, notEmpty: true}),
    age: integerFormat({min: 18, max: 99, notEmpty: true}),
    friends: [integerFormat({naturalNumber: true, notZero: true})]
})

module.exports = async input => {
    const result = await formatTest(inputs)
}

Promise value test with custom error class constructor

const { 
    UserInputError
} = require('apollo-server')

const formatTest = promiseFormat({
    name: stringFormat({capitalize: 'words', min: 2, max: 20, trim: true, notEmpty: true})
})

// if error is thrown, it will be passed to class constructor first, then rejected by promise
// useful when you want to throw a specific class of error
module.exports = async input => {
    const result = await formatTest(inputs, UserInputError)
}

String format configuration

const stringTest = stringFormat({capitalize: 'words'})

// sanitize
trim,           // trim string [boolean]
trimLeft,       // trim string from left side [boolean]
trimRight,      // trim string from right side [boolean]
toLowerCase,    // mutate string character to lower case [boolean]
toUpperCase,    // mutate string character to upper case [boolean]
truncate,       // truncate strings lenght to specific lenght [integer]
capitalize,     // capitalize string ['words', 'sentences', 'first']

// validate
notUndef,       // typeof undefined not allowed [boolean]
notEmpty,       // typeof undefined, null, ''(empty string) not allowed [boolean]
enum,           // An array of valid strings, example ['Cat', 'Dog', 'Apple'] [array:<string>]
min,            // requirement for minimum strings length [integer]
max,            // requirement for maximum strings length [integer]
email,          // regExp test for basic email format [boolean], use with ({trim: true, toLowerCase: true})
test            // manual regExp test, example (stringFormat({test: /aaa/}))

Integer format configuration

const integerTest = integerFormat({naturalNumber: true})

// validate
notUndef,       // typeof undefined not allowed [boolean]
notEmpty,       // typeof undefined, null, ''(empty string) not allowed [boolean]
notZero,        // 0 not allowed
naturalNumber,  // 0, 1, 2, etc... allowed
enum,           // An array of valid integer, example [1, 2, 3] [array:<integer>]
min,            // minimum value
max             // maximum value

Float format configuration

const floatTest = floatFormat({naturalNumber: 'words'})

// validate
notUndef,       // typeof undefined not allowed [boolean]
notEmpty,       // typeof undefined, null, ''(empty string) not allowed [boolean]
notZero,        // 0 not allowed
naturalNumber,  // 0, 1, 2, etc... allowed
enum,           // An array of valid floats, example [1.1, 2.1, 3.1] [array:<float>]
min,            // minimum value
max,            // maximum value
positive,       // positive float required
latitude,       // latitude required
longitude       // longitude required       

Boolean format configuration

const booleanTest = booleanFormat({notEmpty: true})

// validate
notUndef,       // typeof undefined not allowed [boolean]
notEmpty,       // typeof undefined, null, ''(empty string) not allowed [boolean]