13

How to accept request content-type of application/vnd.api+json and reject anything else?

Also how can I access the x-api-key value using Koa.js ?

Thanks in advance

Nilanka Manoj
  • 3,527
  • 4
  • 17
  • 48
Roobie
  • 1,346
  • 4
  • 14
  • 24
  • What did you try? – Evert Oct 11 '17 at 05:21
  • if (!ctx.accepts('application/vnd.api+json')) { ctx.throw(406, 'unsupported content-type'); } // but not getting status 406 in Postman. For x-api-key cannot find any documentation – Roobie Oct 11 '17 at 05:25
  • Include a full, reproducible script in your question if you need help! – Evert Oct 11 '17 at 14:38
  • I also had tried if (ctx.is(application/vnd.api+json) { .. } as describe here https://github.com/koajs/koa/blob/master/docs/api/request.md and that didn't work for me so I used a simple comparison if (ctx.request.type=='application/vnd.api+json') { .. } – Roobie Oct 12 '17 at 02:10

2 Answers2

22

To get the header: ctx.get('x-api-key');

Yorkshireman
  • 2,194
  • 1
  • 21
  • 36
8

This is my attempt to the first part of the question, content negotiation:

const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();

//const dataAPI = require('../models/traffic');

router.get('/locations/:geohash/traffic/last-hour', (ctx, next) => {    
    // some code for validating geohash goes here ...

    if (ctx.request.type=='application/vnd.api+json') {        
        //ctx.body = dataAPI.getTrafficData(ctx.params.geohash, 'hours', 1);
        ctx.body = { status: "success" };
        ctx.type = "application/vnd.api+json";
        next();
    }
    else {
       ctx.throw(406, 'unsupported content-type');
       // actual error will be in JSON API 1.0 format
    }
});

I am getting status 406 Not Acceptable and unsupported content-type in Postman when I submit the value for Content-Type in Postman anything that is not application/vnd.api+json. Otherwise, I get station 200 OK and { "status": "success" in the body.

Edited

Haven't found a better to this but below is a quick and dirty way to extract the value of x-api-key. It works for my purpose:

var key = ctx.request.headers['x-api-key']
Roobie
  • 1,346
  • 4
  • 14
  • 24