1.2.0 • Published 7 years ago

koa-setincontext v1.2.0

Weekly downloads
1
License
ISC
Repository
github
Last release
7 years ago

koa-setincontext

Flexible middleware for Koa 2 that lets you set properties to the ctx.state for every request.

This is particulary useful when you have dynamic properties which value may change on every request.

Installation

$ npm install koa-setincontext --save

Examples

Simple usage:

import Koa from 'koa';
import setInContext from 'koa-setincontext';

const app = new Koa();
const events = ['one', 'two', 'three'];

app.use(setInContext('events', events));

app.use(async (ctx, next) => {
    console.log(ctx.state.events) // => ['one', 'two', 'three']
    return await next();
})

With an object

import Koa from 'koa';
import setInContext from 'koa-setincontext';

const app = new Koa();
const events = ['one', 'two', 'three'];

app.use(setInContext({
    name: 'events',
    value: events
}));

app.use(async (ctx, next) => {
    console.log(ctx.state.events) // => ['one', 'two', 'three']
    return await next();
})

With an array of objects:

import Koa from 'koa';
import setInContext from 'koa-setincontext';

const app = new Koa();
const events = ['one', 'two', 'three'];

app.use(setInContext([
    {
        name: 'another',
        value: 'awesome'
    },
    {
        name: 'events',
        value: events
    }
]));

app.use(async (ctx, next) => {
    console.log(ctx.state.another) // => 'awesome'
    console.log(ctx.state.events) // => ['one', 'two', 'three']
    return await next();
})
1.2.0

7 years ago

1.1.0

7 years ago

1.0.10

7 years ago

1.0.9

7 years ago

1.0.8

7 years ago

1.0.7

7 years ago

1.0.6

7 years ago

1.0.5

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago