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

koa-router-joi-validation

v1.2.2

Published

Koa input/output validation middleware for Koa router

Downloads

1,128

Readme

koa-router-joi-validation

npm node Build Status codecov Maintainability David deps Known Vulnerabilities NPM

NPM

⚡️Super Light, configurable Koa router validator middleware that uses Joi.⚡️

Install

npm install koa-router-joi-validation -S

Why

  • It uses Joi (The most powerful schema description language and data validator for JavaScript.)
  • Input validation (query, params, body, headers).
  • Output validation, based on the HTTP returned code from the router 200, 204 ...etc.
  • Configurable.
  • It does only one thing (validation) and it does it right.
  • Loose coupling with koa-router, means:
    • Built-for koa-router and NOT [koa-router Built-in].
    • Standard routes function signature.
    • Clean changelog and No unnecessary updates (it always concerns the package itself).
    • Always have access to await next().
    • Tiny codebase.
  • 100% 🔥 test coverage.

Usage

The middleware function takes an object as argument

import validate, { Joi } from ('koa-router-joi-validation');
.....
    validate({
      query: // Joi schema object
      body: // Joi schema object
      params: // Joi schema object
      headers: // Joi schema object
      200: // Joi schema object
      503: // Joi schema object
      .....
      config: {
        denyUnknown: [],
        httpErrorCode: 400,
        nextOnError: false,
        alternate: []
      }
    }),
.....

validate(object)

The object contains the next keys:

| Key | Type | Validates | Note | | -------- | :---------------: | ------------------ | ---------------------------------------------------------------------------------------- | | query | Joi Schema Object | ctx.query | | | params | Joi Schema Object | ctx.params | | | headers | Joi Schema Object | ctx.headers | | | body | Joi Schema Object | ctx.request.body | ⚠️ use a body parser e.g. koa-bodyparser | | 200..503 | Joi SchemaObject | ctx.body | when ctx.status === 200..503 | | config | Object | | Use it to change the validator behavior: |

config

  • denyUnknown

    allow/disallow undeclared values in the schema

    Type array.

    default [].

    e.g. denyUnknown["headers"] the request fail ONLY if all the headers entries are declared in schema.

  • httpErrorCode

    The returned http error code when the validation fails

    Type int HTTP code (400... 503)

    default 400 (Bad request)

  • nextOnError

    If true, the validator will not throw an error and the execution flow will continue (await next())

    ⚠️ Note: in that case the validation error will be found in ctx.state.routeValidationError

    Type bool

    default false

  • alternate

    Allows alternative validation in the schema. It is a wrapper of Joi's alternatives function.

    Type array.

    default [].

    e.g. alternate["body", "query"] alternative validation will be applied on the request's query and body parameters. The request fails if both are incorrect. If any parameter from the list succeed the validation, request will pass and continue the execution flow.

Example

import Koa from "koa";
import Router from "@koa/router";
import validate, { Joi } from ('koa-router-joi-validation');

const app = new Koa();
const router = new Router()

router.get(
    "/hello/:id",
    validate({
      query: {
        q: Joi.string().required()
      },
      params: {
        id: Joi.string().required()
      },
      headers: {
        "Content-Type": Joi.string()
          .valid("application/json", "application/javascript")
          .required()
      },
      200: {
        succuss: Joi.bool()
      }
    }),
    async (ctx, next) => {
      ctx.body = {
        succuss: true
      };
      await next();
    }
  );

app.use(router.routes());

Licences

MIT