2

I am using nodejs koa rest api service. And I want to pass a parameter to validation middleware.

But I also need to pass context.

How can I correctly use middlewares with koa2

//route.js
const Router = require('koa-router')

const auth = require('../middlewares/auth')
const controller = require('../controllers').editorsController

const schemas = require('../schemas/joi_schemas')
const validation = require('../middlewares/validation')

const router = new Router()

const BASE_URL = `/editors`

router.get('/protected', auth, controller.protected)
router.get(BASE_URL, controller.getEditors)
router.post(BASE_URL, auth, validation(schemas.editorPOST, 'body'), controller.addEditor)

module.exports = router.routes()
//validation.js
const Joi = require('joi')

module.exports = (schema, property, ctx, next) => {
  const { error } = Joi.validate(ctx.request[property], schema)
  console.log(error)
  const valid = error == null
  if (valid) {
    next()
  } else {
    const { details } = error
    const message = details.map(i => i.message).join(',')

    ctx.status = 422
    ctx.body = {
      status: 'error',
      message: message
    }
  }
}
//joi_schemas.js
const Joi = require('joi')
const schemas = {
  editorPOST: Joi.object().keys({
    username: Joi.string().required(),
    password: Joi.string().required(),
    enable: Joi.number()
  })
}
module.exports = schemas

I get some errors:

Cannot read property 'request' of undefined

Or any other solutions?

Benfactor
  • 543
  • 4
  • 11
  • 31

1 Answers1

3

ctx.request is undefined because ctx wasn't passed as an argument:

validation(schemas.editorPOST, 'body')

And ctx it's unavailable in the scope where the middleware was called.

If a middleware needs to be parametrized, it should be higher order function:

module.exports = (schema, property) => (ctx, next) => {
 ...
Estus Flask
  • 206,104
  • 70
  • 425
  • 565