Coder Social home page Coder Social logo

aeberdinelli / schemy Goto Github PK

View Code? Open in Web Editor NEW
14.0 3.0 1.0 340 KB

Schemy is an extremely simple, lightweight schema validation library.

Home Page: https://www.npmjs.com/package/schemy

JavaScript 100.00%
node javascript validation schema json joi mongoose library nodejs typescript

schemy's Introduction

Schemy is an extremely simple, lightweight yet powerful schema validation library. Perfect for lightweight-oriented projects like cloud functions where size and speed are key features. It weights less than 18 KB!

Usage

Install using npm: npm install --save schemy. Then, create a schema with the desired properties and their types:

const Schemy = require('schemy');

const characterSchema = new Schemy({
    'name': {
        type: String,
        required: true
    }
});

// Validate against input data
if (!characterSchema.validate(someData)) {
    characterSchema.getValidationErrors(); // => [ 'Missing required property name' ]
}

// You can also validate asynchronously
await Schemy.validate(someData, characterSchema);

Plugins

Schemy can be easily extended with new functionality. For example, this adds a feature to reference properties within the schema.

// Require the plugin
const ReferenceSupport = require('schemy-reference-support');

// Call Schemy.extend() with the plugin or with an array of plugins
Schemy.extend(ReferenceSupport);

new Schemy({
    password: String,
    confirm: Schemy.$ref('password')
});

You can check the whole list of available plugins in the wiki ↗

API

Static methods

Instance methods


Full documentation ↗️

schemy's People

Contributors

aeberdinelli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

schemy's Issues

Schemy instance persisting validation errors on succesive invocations of AWS lambda function

Hi again!!
I have noticed an error regarding validation errors since version 3.2.1 , when using schemy on lambda functions errors are being propagated between lambda invocations.

I am almost certain that the cause is this change here
image

On version 3.2.0 the validationErrors array was being cleared on every invocation, now if this array comes with validation errors from a previous lambda invocation (since aws lambdas preserve all static code as long as the instance doesn't die) it doesn't get into that if statement and the validationErrors array wont be cleared

Incorrect validations when using child schemy instances

There's an issue when you have child Schemy instances, for example:

it("Should pass validation with correct child schemas using strict property", function () {
    const nameSchema = new Schemy(
      {
        firstname: {
          type: String,
          required: true,
        },
        lastname: {
          type: String,
        },
      },
      { strict: false }
    );

    const personSchema = new Schemy(
      {
        name: { type: nameSchema, required: true },
        age: { type: Number, required: true },
      },
      { strict: false }
    );

    const payload = {
      name: {
        firstname: "Joaquin",
        lastname: "Arreguez",
        secondName: "Eduardo",
      },
      age: 28,
      address: "Avenida Siempre Viva 666",
    };

    const result = personSchema.validate(payload);

    expect(result).toBe(true);
  });

Whenever there is an object property in the body being validated, it will try it as a child schema that it should instantiate, even if it is actually a Schemy instance.

We should add a condition to prevent creating a new Schemy instance if the value is already one.

Internal calls to new Schemy() not allowing 'Schemy Settings'

Dentro del contructor hay varias llamadas a new Schemy() cuando se hacen parseos automaticos de datos, por ej para generar instancias de schemy de objetos dentro de arrays u objetos anidados donde no está la posibilidad de pasar 'settings' como {strict:false} para modificar el funcionamiento de esa instancia de Schemy.

Ésto pasa en todas las llamadas internas de new Schemy(), no se tiene en cuenta que es posible querer pasar settings como permite el constructor constructor(schema, { strict } = {})

Por ej dentro de async validate

static async validate(body, schema, includeAll = false, orderBody = false) {
		if (!(schema instanceof Schemy)) {
			schema = new Schemy(schema);
		}

		return new Promise((resolve, reject) => {
			if (schema.validate(body)) {
				return resolve(
					schema.getBody(includeAll, orderBody)
				);
			}

			return reject(schema.getValidationErrors());
		});
	}

O del constructor cuando una propiedad es un objeto

else if (typeof properties === 'object') {
						try {
							const parsed = {};
	
							if (schema[key].custom) {
								const { custom } = schema[key];
								parsed.custom = custom;
							}
	
							parsed.type = new Schemy(properties);
							parsed.required = !!properties.required;
	
							schema[key] = parsed;
						} catch (err) {
							throw `Could not parse property ${key} as schema`;
						}
					}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.