egg-plugin-context
v1.1.1
Published
An egg middleware for adding contexts
Downloads
17
Maintainers
Readme
egg-plugin-context
An egg plugin for handle context
Install
# use pnpm
$ pnpm install egg-plugin-context
# use npm
$ npm install egg-plugin-context --save
# use yarn
$ yarn add egg-plugin-context
Usage
Enable context plugin
// {app_root}/config/plugin.js
exports.withContext = {
enable: true,
package: 'egg-plugin-context'
}
1. Simple use
// {app_root}/router.js
module.exports = app => {
const { router, controller, middleware } = app
router.post('/api/test', middleware.withContext({ token: 100 }), controller.test)
}
// ctx.context.token === 100
2. Arguments passed into function
// {app_root}/router.js
module.exports = app => {
const { router, controller, middleware } = app
router.post(
'/api/test',
middleware.withContext(ctx => ({ test: 100 })),
controller.test
)
}
// ctx.context.test === 100
3. Arguments passed into async function
// {app_root}/router.js
module.exports = app => {
const { router, controller, middleware } = app
router.post(
'/api/test',
middleware.withContext(async ctx => Promise.resolve({ test: 100 })),
controller.test
)
}
// ctx.context.test === 100
Options
contextName
The contextName determines where to get the Context, like: ctx.context
// {app_root}/router.js
module.exports = app => {
const { router, controller, middleware } = app
router.post(
'/api/test',
middleware.withContext({ token: 100 }, { contextName: 'contextData' }),
controller.test
)
}
// ctx.contextData.token === 100
Change logs
Questions & Suggestions
Please open an issue here.