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

@fehujs/validator

v0.1.2

Published

Object validator for requests

Downloads

87

Readme

@fehujs/validator

This module permits you to parse objects (like request, body) to verify if its processable.

Usage

Note about running: if you want to use the custom rules system, please make sure that your current working directory is the root of your project.

Here's a sign up view process using the validator module:

    const schema = await Schema.create({
        name: {
            "optional": ["John Doe"]  // you can set a default value if you want (if the field is empty, the default value will be set)
        },
        email: {
            "email": []
        },
        password: {
            "min": [8]
        }
    })
    const body = await schema.parse<SignupPayload>(await getPostBody(req))
    let user: ModelObject | null

    if (!body.success) {
        // error: the body doesn't math with the schema 
    }

    try {
        user = await User.create({
            name: body.data.name,
            email: body.data.email,
            password: body.data.password
        })
    } catch (err: any) {
        // error: error while creating user (email already taken, ...)
    }

The first part consists to defining our schema. The schema is an object which keys will be the fields of the parsed object (here, the request body). In each key, you can put an object containing the rules that the field must comply with.

A simple draft of what it means:

{
    field1: {
        rule1: ["rule1 param1", "rule1 param2"]
        rule2: ["rule2 param1"]
    },
    field2: {
        rule3: []
    }
}

Then comes the request parsing: await schema.parse<SignupPayload>(await getPostBody(req))

You specify in parameters of the async method schema.parse() the object to parse, and you must provide the output type.

Let's say that

type SignupPayload = {
    name: string
    email: string
    password: string
}

To the schema.parse() output will be typed as

{
    success: boolean
    data: SignupPayload
}

So you can verify if the parsing is a success or not with success.

If the parsing is a success, you can get the parsed data by accessing to (in this example) body.data.

Note: if the parsing isn't valid, the data object will contain the errors of each field.

E.g: if the request body was something like

{
    email: "e",
    password: "123"
}

the schema.parse() return would be

{
    success: false,
    data: {
        name: "",
        email: "Invalid email",
        password: "Text isn't long enough, excepted a 8 characters minimum text"
    }
}

Validators directory

You can set your schemas in files contained into src/app/validators.

Create custom rules

If you want to create a custom rule, you can create a file named rules.ts into src/app/validators.

Nota (this isn't supported yet): you can decide to put it somewhere else but you'll need to update the path in your app config.

Then, begin to implement your rules!

import type { Rule } from "#validator"

export const customRule = (str: string) => {
    return {
        name: "Custom rule name",
        errMsg: "Custom rule error message",
        cb: () => {
            if (/** your condition */) return true

            return false
        }
    } as Rule
}

Now you can easily use this rule in your schemas:

    // ...
    "customRule": [],
    // ...

Note: the first argument of the function is provided by the module, so in the schema declaration you MUST NOT set it as a rule param. The next arguments MUST be set into the schema declaration.

Here's an example:

export const myCustomMin = (str: string, min: number, foo: string) => {
    return {
        name: "Custom minimum string length",
        errMsg: "The string isn't long enough (custom rule)",
        cb: () => {
            console.log(foo)

            if (str.length >= min) return true

            return false
        }
    } as Rule
}

As you can see, we added a parameter named min and another named foo. In the schema, the declaration would look like this:

    // ...
    "myCustomMin": [
        8, // min param
        "bar" // foo param
    ],
    // ...

Please note that the params are handled in the order of declaration, do not put the foo param before the min param.