Giter Club home page Giter Club logo

osom's Introduction

osom

An Awesome [/osom/] Object Data Modeling. Inspired in mongoose but Database Agnostic.

Last version Coverage Status NPM Status

Installation

$ npm install osom --save

Preview

const osom = require('osom')

function trim (str) {
  return str.trim()
}

function isValidTitle (str) {
  return str.length > 0
}

// setup your schema
const schema = {
  title: {
    type: String,
    validate: isValidTitle,
    transform: [trim]
  },
  category: String,
  type: String,
  source: String,
  link: String,
  createdAt: String,
  updatedAt: String
}

// create validator based on schemas
const validator = osom(schema)

// validate it!
validator({ title: '  23  ' }) // => {title: '23'}

Usage

osom(schema, [global])

where:

  • schema: It represents a set of rules (one per each key) that will be used for validate an object.
  • global (optional): It brings you the possibility to declare global rules definition as helper to avoid write repetitive code.

After that, you will have a validator function that you can invoke passing the object to be validate.

Schema

Simple

The most common use case is validate the type of something.

If you are only interested in the type, you can provide a simple schema like:

const simpleSchema = {
  age: Number
}

Where key is the name of the rule and value the type of it.

Advanced

The basic mode is a simplification of the advanced mode for the most common use case.

While in basic mode only is possible setup type, in advanced mode you can setup more things providing a configurable object.

Each key of the object represent a rule . It's possible setup different things in the same rule.

Defining Rules

type

Type: function

As in basic mode, it specifies the type of the output value:

const schema = {
  age: {
    type: Number
  }
}

Internally it uses chaste. This makes easy casting compatible types:

const schema = {
  age: {
    type: Number
  }
}

const validator = osom(schema)
validator({ age: '23' }) // => {age: 23}

casting

Type: boolean
Default: true

It enable/disable type casting. An TypeError will be throwed under different type evaluation.

const schema = {
  age: {
    type: String,
    casting: false
  }
}

const validator = osom(schema)
validator({ age: '23' }) // => TypeError("Expected a {string} for 'age'.")

required

Type: boolean|string
Default: false

It marks a rule as required field and throws TypeError if value for the field is not present.

Additionally is possible provide a custom error message. For do it, pass an String.

const schema = {
  age: {
    type: String,
    required: 'sorry but you must provide an age.'
  }
}

const validator = osom(schema)
validator({}) // => TypeError("sorry but you must provide an age")

default

Type: string|object|number|boolean|function
Default: null

It sets a default value if nill value as input is provided.

Additionally you can provide a function for set a dynamic value:

const schema = {
  age: {
    type: Number, default: function () { return 23 }
  }
}

const validator = osom(schema)
validator({}) // => { age: 23 }

transform

Type: function|array
Default: []

It transforms the input value.

The Methods provided in the array are applied as pipeline (the input of the second is the output of the first).

function trim (str) {
  return str.trim()
}

const schema = {
  age: {
    type: String,
    transform: [trim]
  }
}

const validator = osom(schema)
validator({ age: '    23   ' }) // => { age: '23' }

validate

Type: function|object
Default: null

It set up a function that will be exec to validate the input value. If it fails, it throws TypeError.

const schema = {
  age: {
    type: String,
    validate: function (v) {
      return v === '23'
    }
  }
}

const validator = osom(schema)
validator({ age: 25 }) // => TypeError("Fail '25' validation for 'age'.")

Providing a object brings you the possibility set up a custom error message:

const schema = {
  age: {
    type: String,
    validate: {
      validator: function (v) {
        return v === '23'
      },
      message: 'expected a millenial value instead of %s!'
    }
  }
}

const validator = osom(schema)
validator({ age: 25 }) // => TypeError("expected a millenial value instead of 25!")

Defining Global Rules

While is possible provide specific setup per each rule, also is possible provide them as global to apply to all rules.

This minimizes the schemas definitions.

function trim (str) {
  return str.trim()
}

const schema = {
  age: {
    type: String
  }
}

const globalFields = {
  transform: [trim]
}

const validator = osom(schema, globalFields)
validator({ age: '  23  ' }) // => {age: '23'}

No problem if later you need to avoid it for a specific case.

function trim (str) {
  return str.trim()
}

const schema = {
  age: {
    type: String,
    transform: []
  }
}

const globalFields = {
  transform: [trim]
}

const validator = osom(schema, globalFields)
validator({ age: '  23  ' }) // => {age: '  23  '}

Tips

Working with async code

This library works synchronously.

However, you can use it comfortably in a async workflow transforming the interface into a callback/promise style.

For example, consider use async#asyncify for do it. we could have a schema.js file like:

const schema = osom({
  title: {
    type: String,
    validate: isValidTitle,
    transform: [trim]
  },
  category: String,
  type: String,
  source: String,
  link: String,
  createdAt: String,
  updatedAt: String
})

module.exports = async.asyncify(schema)
module.exports.sync = schema

Then you only need use it into a async workflow:

const schema = require('./schema')
schema(data, function (validationError, instance) {
  /** do something */
})

Be careful: this transformation doesn't mean that the function works now asynchronously; Just is converting try-catch interface into callback(err, data).

License

MIT © Kiko Beats

osom's People

Contributors

abpai avatar dependabot-preview[bot] avatar dependabot[bot] avatar greenkeeper[bot] avatar greenkeeperio-bot avatar kikobeats avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

osom's Issues

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Once you have installed CI on this repository, you’ll need to re-trigger Greenkeeper’s initial Pull Request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper integration’s white list on Github. You'll find this list on your repo or organiszation’s settings page, under Installed GitHub Apps.

An in-range update of kind-of is breaking the build 🚨

Version 6.0.1 of kind-of was just published.

Branch Build failing 🚨
Dependency kind-of
Current Version 6.0.0
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

kind-of is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • coverage/coveralls Coverage pending from Coveralls.io Details
  • continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 5 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

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.