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

tramway-validation-joi

v0.1.0

Published

A joi validation adapter for the Tramway framework

Downloads

6

Readme

Tramway Joi Validation is a simple adapter to integrate joi validation with Tramway Validation. It includes:

  1. The Joi Provider
  2. The necessary mappings to integrate with Tramway

See the joi documentation for options and settings that can be used with the custom schema.

Installation:

  1. npm install --save tramway-core-validation tramway-validation-joi

Getting Started

With dependency injection you can add the following entries to your services config files. Be sure to do the same with your plugin.

In this example, we set up everything that's needed for validation with joi in the src/config/services/validation.js file and add the necessary mappings to the parameters in src/config/parameters/global.

import ValidationService, {Mapper} from 'tramway-core-validation';
import JoiValidationProvider, {JoiSchemaFactory} from 'tramway-validation-joi';

export default {
    "service.validation": {
        "class": ValidationService,
        "constructor": [
            {"type": "service", "key": "provider.validation:joi"},
            {"type": "service", "key": "factory.validation:joi"},
        ],
    },
    "provider.validation:joi": {
        "class": JoiValidationProvider,
    },
    "factory.validation:joi": {
        "class": JoiSchemaFactory,
        "constructor": [
            {"type": "service", "key": "mapper.validation:joi"},
        ],
    },
    "mapper.validation:joi": {
        "class": Mapper,
        "constructor": [
            {"type": "parameter", "key": "joi_mapping"}
        ],
    },
};

Then add a validation.js file under src/config/parameters/global:

import {
    JoiMapping,
} from 'tramway-validation-joi';

export default {
    "joi_mapping": JoiMapping,
};

Then in the index.js under src/config/parameters/global:

import app from './app';
import cors from './cors';
import port from './port';
import routes from './routes';
import validation from './validation;

export default {
    app,
    cors,
    port,
    routes,
    ...validation,
}

Creating your first schema

The new Schema class contains static helper methods to help assign types to your values. Your Schema should have the same properties as the Entity class you want to validate.

Example:

The following example assumes you use babel-plugin-transform-class-properties as part of your babel plugins. The same can be achieved via the constructor.

For the following entity: entities/Sample.js:

import {Entity} from 'tramway-core-connection';

export default class Sample extends Entity {
    id;
    name;
    email;
    card;
    age;
    token;
    password;
}

The following schema:

import {Schema} from 'tramway-core-validation';

export default class Sample extends Schema {
    id = Schema.guid().required();
    name = Schema.string();
    email = Schema.email();
    card = Schema.creditCard();
    age = Schema.intRange(18, 100);
    token = Schema.token().excludes('password');
    password = Schema.string({minLength: 5}).excludes('token');
}

Validating an instance of the entity against the schema

You can use the validate method on the Validate Service wherever it is used.

import {Sample} from '../entities';
import {Sample as SampleSchema} from '../schemas';

...

let sample = new Sample();

...

try {
    sample = this.validationService.validate(sample, new SampleSchema());
} catch (e) {
    //handle the validation exception
}

Schema helper methods

All Schema helper methods return an instance of SchemaMeta which includes some extra configurations to the following:

| Method | Arguments | Description | | --- | --- | --- | --- | | regex | RegExp | String must satisfy RegExp | | range | min: number, max: number | Ensures number is within the range | | intRange | min: number, max: number | Ensures number is within the range and is an integer | | string | {length: number, minLength: number, maxLength: number, truncate: boolean, uppercase: boolean, lowercase: boolean} | Ensure value is a string and optionally meets certain characteristics | | number | | Ensures value is a number | | email | options: Object | Ensures string is an email with configurable options | | entity | entityName: string | Ensures an object is a certain type of entity | | creditCard | | Ensures the string is a valid credit card number | | token | | Ensures the string is a valid token | | ip | {version, cidr} | Ensures the string is a valid ip address | | uri | {scheme, allowRelative, relativeOnly, allowQuerySquareBrackets} | Ensures the string is a valid uri | | guid | {version} | Ensures the string is a valid guid or uuid | | isoDate | | Ensures the string is an iso-formatted date string | | timestamp | type: 'unix'/'javascript' | Ensures a number is a valid timestamp | | date | {min, max, greater, less} | Ensures the validity of a date with optional constraints | | custom | provider schema object | Let's you use a schema that is specific to a validation provider |

The SchemaMeta instance which will be saved allows you to set some additional information using a fluent interface.

| Method | Arguments | Description | | --- | --- | --- | | required | | Sets the schema value to be required | | default | value: any | Sets a default value to apply if none is set | | accompanies | ...keys: string | A list of keys that must be present when the corresponding key is present | | excludes | ...keys: string | A list of keys that must not be present when the corresponding key is present |