1.1.1 • Published 12 months ago

egg-plugin-context v1.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

egg-plugin-context

An egg plugin for handle context

NPM version Codacy Badge Known Vulnerabilities npm download License

Sonar

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

Change logs

Questions & Suggestions

Please open an issue here.

License

MIT