Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to pass values among middlewares in koa.js

I have a simple setup for koa.js with koa-route and koa-ejs.

var koa     = require('koa');
var route   = require('koa-route');
var add_ejs = require('koa-ejs');
var app     = koa();

add_ejs(app, {…});

app.use(function *(next){
    console.log( 'to do layout tweak for all requests' );
    yield next;
});

app.use(route.get('/', function *(name) {
  console.log( 'root action' );
  yield this.render('index', {name: 'Hello' });
}));

What's the best way to pass values between those two methods?

like image 613
beatak Avatar asked Jun 16 '14 03:06

beatak


2 Answers

context.state is the low-level way of sharing data between middleware. It's an object mounted on context that's available in all middleware.

You can use it like so:

let counter = 0;

app.use((ctx, next) => {
  ctx.state.requestId = counter++;
  return next();
});

app.use((ctx, next) => {
  console.log(ctx.state.requestId);
  // => 1, 2, 3, etc
  return next();
});

source

koajs readme

like image 85
jbielick Avatar answered Oct 22 '22 10:10

jbielick


You can use Koa Context:

app.use(function *(next) {
  this.foo = 'Foo';
  yield next;
});

app.use(route.get('/', function *(next) { // 'next' is probably what you want, not 'name'
  yield this.render('index', { name: this.foo });
  yield next; // pass to the next middleware
}));
like image 34
realguess Avatar answered Oct 22 '22 10:10

realguess