Socket
Book a DemoInstallSign in
Socket

@revmob/raml-validator

Package Overview
Dependencies
Maintainers
8
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@revmob/raml-validator

Project used for documenting and validating APIs

0.2.1
latest
Source
npmnpm
Version published
Maintainers
8
Created
Source

RAML Validator

Welcome to a new era. An era where we, revmobers, will document every API! 😎

Why

Because loggin the input payload and response json to understand what's going on sucks 😭

To help us, we will use RAML (RESTful API Modeling Language) to document our code, and complementary libs (osprey) to validate requests against our doc.

What is does

Before your request reaches your controllers, raml express middleware will:

  • intercept the request;
  • check where it was going to;
  • validate them against a raml file;
  • return an error if the request payload doesn't meet the criteria

Default Error Handler

The default error handler will return array of error:

400:
  body:
    type: object
    properties:
      errors: error[]
    examples:
      invalidResponse:
        errors: [{
            message: 'Validation Error!',
            details: {
                age: 'Missing required property: age',
                name: 'Invalid type, expected string'
            }
        }]

The response:

{
    "errors": [{
        "message": "Validation Error!",
        "details": {
            "age": "Missing required property: age",
            "name": "Invalid type, expected string"
        }
    }]
}

Installation

Just do a:

npm install --save @revmob/raml-validator

How to use

To see an example, just access examples/express.js. The default middleware is created Asyncronously, using promise. That being said, just pass your Express instance to raml-validator like this: ALWAYS define raml-validator middleware BEFORE your routes, otherwise it won't validate your request before your controller processing it


import ramlValidator from 'raml-validator'

const config = {
  path: 'path/to/api.raml'
}

const app = express()

ramlValidator(config)
  .then(({ validator, errorHandler, finalErrorHandler }) =>
    app.use(validator) // MUST come before your routes
     .use(errorHandler) // MUST come before your routes
     .use(myRoutes)
     .use(finalErrorHandler) // SHOULD be the last
   )
  .then(app => app.listen(8080))

Configuration

Osprey

The config object accepts the following:

const config = {
  path: 'path/to/api.raml', //ABSOLUTE path to raml file
  customErrorHandler: function (req, res, errors, stack) {
    // A custom Error Handler, where you can process invalid requests your way.
  },
  server: {
    cors: true
  },
  security: {
    basicAuth: {
      validateUser: (user, password, done) => {
        if (user === MY_USER && password === MY_PASSWORD) {
          return done(null, true)
        }

        return done(null, false)
      }
    }
  }
}

For more details, please refer to osprey documentation for server and security.

Additional configuration

As of 0.2.0, this package expose the hooks configuration.

This allows you to intercept RAML errors. It's specially useful for logging:

There are 2 different hooks:

  • onValidationError :: (errors: Error[], req: HttpRequest, res: HttpResponse) -> void: will be called if RAML validation fails.
  • onUnknownError :: (error: Error, req: HttpRequest, res: HttpResponse) -> void: will be called if something goes wrong with the validation setup.
const config = {
  path: 'path/to/api.raml',
  server: {
    cors: true
  },
  security: {
    basicAuth: {
      validateUser: (user, password, done) => {
        if (user === MY_USER && password === MY_PASSWORD) {
          return done(null, true)
        }

        return done(null, false)
      }
    }
  },
  hooks: {
    onValidationError: (errors, req, res) => {
      errors.map(error => console.log(error))
    },
    onUnknownError: (error, req, res) => {
      console.log(error)
    }
  }
}

I am a hipster and don't use Express.js

If you're not using express.js server, feel free to contribute by PRing a new raml middleware! :)

FAQs

Package last updated on 28 Sep 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.