Skip to content

xpepermint/koa-strong-params

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

koa-strong-params

Build Status NPM version Dependency Status

Rails-style implementation of strong parameters for Koa. The middleware adds the this.params object to the Koa context which returns an object, built from query string and request body data. The returned object has some useful methods allows for data requiring and filtering.

You should consider using koa-qs and koa-bodyparser packages together with koa-strong-params.

Installation

Install the npm package.

npm install koa-strong-params --save

Attach the middleware.

var koa = require('koa');
var params = require('koa-strong-params');
var app = koa();
app.use(params());

Example

var koa = require('koa');
var params = require('koa-strong-params');
var bodyparser = require('koa-bodyparser');
var qs = require('koa-qs')
var app = koa();
qs(app); // required for nested query string objects
app.use(bodyparser()); // required for params to include request body objects
app.use(params());
app.use(function *() {

  // all available params
  this.body = this.params.all();
  // -> { id: '13', name: 'Bob', age: '13', email: '[email protected]', address: { country: 'US', street: '261 West' }}

  // only selected params
  this.body = this.params.only('name', 'age');
  // -> { name: 'Bob', age: '13' }

  // all params except those provided
  this.body = this.params.except('name', 'id', 'address');
  // -> { id: '13', age: '13', email: '[email protected]' }

  // all params of a sub-object
  this.body = this.params.require('address').all();
  // -> { country: 'US', street: '261 West' }

  // only selected params + some merged attributes
  this.body = this.params.merge({ badge: 'coder' }).only('name');
  // -> { name: 'Bob', badge: 'coder' }

});
app.listen(3001);

About

Rails-style implementation of strong parameters for Koa

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published