basic-valid-object-schema

0.2.3-alpha.1 • Public • Published

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 contacto.fritzlerilan@gmail.com (http://github.com/ifritzler)

👤 Federico Lautaro Hanson hanson.federico@gmail.com (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 contacto.fritzlerilan@gmail.com (http://github.com/ifritzler).

This project is Apache 2.0 licensed.


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

Package Sidebar

Install

npm i basic-valid-object-schema

Weekly Downloads

2

Version

0.2.3-alpha.1

License

Apache-2.0

Unpacked Size

68.2 kB

Total Files

13

Last publish

Collaborators

  • fedelh