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

basic-valid-object-schema

v0.2.3-alpha.1

Published

Validation tool or utility that allows for simple and fast validation of an object against a schema.

Downloads

30

Readme

Welcome to Basic Valid Object Schema 👋

Version Prerequisite Prerequisite English- Documentation Spanish- Documentation Maintenance License: Apache 2.0


Alpha Version alert

This is an alpha version of the library and is subject to frequent changes and updates. We do not recommend using this version in production environments.

Please note that there may be breaking changes as we work towards the stable release version 1.0.

We do not assume responsibility for any changes made to the API due to the use of this alpha version.

Please be aware that this software is released under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). 

Validation tool or utility that allows for simple and fast validation of an object against a schema.

🏠 Homepage

Prerequisites

  • npm >=8.0.0
  • node >=14.0.0

Install

npm install basic-valid-object-schema

Run tests

npm run test

Supported Data Types

| Data Type | Description | |-----------|-------------| | number | Integers and floating point numbers. | | string | Text string. | | boolean | True or false value. | | null | Null value, represents the absence of a value. | | undefined | Undefined value, represents a variable without an assigned value. | | symbol | Unique and immutable value used as an object key. | | bigint | Extremely large integers (as of ES2020). | | array | Set of grouped data. |


Methods

ValidationObject.prototype.constructor(schema: object)

ValidationObject.prototype.validate(o: object)

  • Method that validates an object against the schema initialized in the ValidationObject instance.
  • Return: {errors: object, data: null | object, isValid: boolean}

validate(schema: object, o: object): Promise<{errors, data, isValidate}>

  • Return: Promise<{errors: object, data: null | object, isValidate: boolean}>

validateSync(schema: object, o: object): {errors, data, isValidate}

  • Return: {errors: object, data: null | object, isValidate: boolean}

Usage/Examples

Basic Example

First, we create a schema. A schema is an object that represents an entity or object to be validated. Each object we want to validate will be validated against the requirements of this schema.

Once the schema is created, wherever we want to perform the validation, we will need to import the library and use 'validate' hook passing the schema and the object to validate. This will give us important variables that we can destructure as seen in the code below.

By default, all properties of a schema are required unless otherwise indicated.

import { validate } from 'basic-valid-object-schema';

const createProductSchema = {
    title: {
        type: "string",
        required: true
    }
    price: {
        type: "number",
        required: true
    },
    active: {
        type: "boolean",
        default: true
    },
    categories: {
        type: "array",
        schema: {
            type: "string"
        },
        default: ["category"],
        required: true
    }
}

const okRawProductData = {
  title: "title1",
  price: 300.5
}

const {
  // Boolean that indicates whether the object is valid or not
  isValid,
  // Validated object, can be null or an object with processed data ready to be used.
  data,
  // Error object produced during validation, can be null if the object is valid.
  errors
} = await validate(createProductSchema, badRawProductData);

console.log({ errors, isValid, data });
/*
errors: null,
isValid: true,
data: {
  title: "title1",
  price: 300.5,
  active: true,
  categories: ["category"]
}
*/ 
...

Example with the same schema and different input that causes the validation to fail and return an error.


const badRawProductData = {
  title: "title1",
  price: "$300.5"
};

const { isValid, data, errors } = await validate(createProductSchema, badRawProductData);

console.log({ errors, isValid, data });
/*
errors: {
  price: {
    error: "price must be a valid number"
  }
},
isValid: false,
data: null
*/

Options for validate:

| Option | Description | |------------|-------------| | whitelist | If the value is true, it will clean all properties that are not defined in the schema. If the value is false, it will not perform the cleaning and allow the existence of additional properties in the object. This option is useful for validating and ensuring that the data sent to the class object is as expected. |

How to avoid cleaning extra properties from my schema


const okRawProductData = {
  title: "title1",
  price: 300.5,
  extraProperty: true
}

const {
  // Boolean indicating whether the object is valid or not
  isValidate,
  // validated object, can be null or an object with processed data ready to be used.
  data, 
  // object of errors produced during validation, can be null if the object is valid.
  errors
} = validate( createProductSchema, badRawProductData, { whitelist: false } )

console.log({errors, isValidate, data})
/*
errors: null,
isValidate: true,
data: {
  title: "title1",
  price: 300.5,
  active: true,
  categories: ["category"],
  extraProperty: true --> Here is the property thanks to whitelist false attribute
}
*/

Shortcut for schema creation:

There is a way to shorten our schemas by leaving the default schema values to do their magic.

To understand this, it is necessary to understand that:

  • Properties of each schema are required by default.
  • The value of a subschema can be either an object that represents a schema or a string.

The schema seen earlier can be reduced to this:

const createProductSchema = {
    title: "string",
    price: "number",
    active: {
        type: "boolean",
        default: true
    },
    categories: {
        type: "array",
        schema: "string",
        default: ["category"]
    }
}

Authors

👤 Ilan Emanuel Fritzler [email protected] (http://github.com/ifritzler)

👤 Federico Lautaro Hanson [email protected] (http://github.com/FedeLH)

🤝 Contributing

Contributions, issues and feature requests are welcome!

Feel free to check issues page. You can also take a look at the contributing guide.

Show your support

Give a ⭐️ if this project helped you!

📝 License

Copyright © 2023 Ilan Emanuel Fritzler [email protected] (http://github.com/ifritzler).

This project is Apache 2.0 licensed.


This README was generated with ❤️ by readme-md-generator