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-jsonapi-headers

v1.1.3

Published

KoaJS Validate JSON-API Request Headers Middleware

Downloads

19

Readme

koa-jsonapi-headers

KoaJS Validate JSON-API Request Headers Middleware

Build Status
Coverage Status
NPM version

Overview

KoaJS middleware to validate required HTTP request headers for JSON API spec.

This middleware will validate all requests have this header set:

Accept: application/vnd.api+json

This middleware will validate POST, PUT and PATCH requests have this header set:

Content-type: application/vnd.api+json

Validation failure will return HTTP 400 Bad Request with the response text of a collection of objects keyed by "errors" (pretty printed here):

{
  "errors": [
    {
      "code": "invalid_request",
      "title": "API requires header \"Content-type application/vnd.api+json\" for exchanging data."
    }
  ]
}

Code review, suggestions and pull requests very much welcome - thanks!

Install

npm install koa-jsonapi-headers

Usage

This middleware will throw a nested object in the application error like so:

  this.throw(400, {
    message: {
      errors: [
        {
          code: 'invalid_request',
          title: 'API requires header "Content-type application/vnd.api+json" for exchanging data.'
        }
      ]
    }
  });

It's designed this way so that the application logging will log the entire JSON response and then rethrow the JSON error message.

Therefore you need to use some application logging like koa-json-logger or catch and rethrow the error yourself.

Here's an example using koa-json-logger:

var koaJsonLogger = require('koa-json-logger');
var koaJsonApiHeaders = require('koa-jsonapi-headers')

app.use(koaJsonLogger({jsonapi: true}));
app.use(koaJsonApiHeaders());

Here's an example of manual catch and re-throw:

var koaJsonApiHeaders = require('koa-jsonapi-headers')

app.use(function *catchJsonApiErrors(next) {
try {
  yield next;
}
catch (err) {

  // Response properties
  this.status = err.status || 500;
  this.body = err.message;
}
this.response.type = 'application/vnd.api+json';
});

app.use(koaJsonApiHeaders());

Exclude List

If you have an API endpoint that you do not want to enforce JSON API headers you can exclude it from the header validations.

There are two methods for excluding:

  • Add jsonapiexclude=true to the URL query string.

Example: http://localhost:3000/signin/google?jsonapiexclude=true

If the URL query string key 'jsonapiexclude' exists (any value) the JSON API headers validation will be skipped.

  • Pass in an exclude list of URL regular expression patterns when you use `app.use()'

Example:

app.use(koaJsonApiHeaders({excludeList: [
    'signin\/google',
    'auth\/google\\?code'
]}));

*Note:

  • No start or end '/'
  • The escaping of the '/' and the double escaping of the '?' as these are regular expression characters.

Tests with code coverage report in test/coverage

Note: Requires nodes at least v0.11.13 (earlier v0.11 versions may work, have not checked for this).

git clone the full repo: git clone [email protected]:rudijs/koa-jsonapi-headers.git

cd koa-jsonapi-headers

npm install

npm test

Code Linting

./node_modules/jshint/bin/jshint lib/*.js

./node_modules/jshint/bin/jshint test/*.spec.js