Skip to content
forked from koajs/json-filter

Middleware allowing the client to filter the response to only what they need, reducing the amount of traffic over the wire.

Notifications You must be signed in to change notification settings

fl0w/json-filter

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

koa-json-filter

Middleware allowing the client to filter the response to only what they need, reducing the amount of traffic over the wire using the ?filter=foo,bar,baz querystring parameter.

JSONSelect would also be great for this but I find it's a little too complicated for the average use-case, so this is just a simple key filter.

Installation

$ npm install koa-json-filter

Options

  • name querystring param defaulting to "filter"

Filtering customization

You may also set ctx.filter to an array of names to filter on, for example by using a header field X-Filter: name,email.

Example

Object responses

Script:

var filter = require('koa-filter');
var koa = require('koa');

var app = koa();

app.use(filter());

app.use(function *(){
  this.body = {
    name: 'tobi',
    email: '[email protected]',
    packages: 5,
    friends: ['abby', 'loki', 'jane']
  }
});

app.listen(3000);
console.log('app listening on port 3000');

Response:

$ GET /?filter=name
{
  "name": "tobi"
}

Array responses

Script:

var filter = require('koa-filter');
var koa = require('koa');

var app = koa();

app.use(filter());

app.use(function *(){
  this.body = [
    {
      name: 'tobi',
      email: '[email protected]',
      packages: 5,
      friends: ['abby', 'loki', 'jane']
    },
    {
      name: 'loki',
      email: '[email protected]',
      packages: 2,
      friends: ['loki', 'jane']
    },
    {
      name: 'jane',
      email: '[email protected]',
      packages: 2,
      friends: []
    },
    {
      name: 'ewald',
      email: '[email protected]',
      packages: 2,
      friends: ['tobi']
    }
  ]
});

app.listen(3000);
console.log('app listening on port 3000');

Response:

$ GET /?filter=name,email
[
  {
    "name": "tobi",
    "email": "[email protected]"
  },
  {
    "name": "loki",
    "email": "[email protected]"
  },
  {
    "name": "jane",
    "email": "[email protected]"
  },
  {
    "name": "ewald",
    "email": "[email protected]"
  }
]

License

MIT

About

Middleware allowing the client to filter the response to only what they need, reducing the amount of traffic over the wire.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%