Skip to content

Koa Context Functions and Properties

Josh Newman edited this page Mar 27, 2018 · 5 revisions

Each context function is added to the Koa 2 context and is available in routes and middleware for any request.

  • A bodyparser is required to use validateBody(). If you aren't using one, I suggest using koa-bodyparser.

  • A router is required to use validateParams(). If you aren't using one, I suggest using koa-router.

#validateBody(validatorSetup: Object, filterSetup: Object)

Validates the incoming body based on the structure and validators given.

ctx.validateBody({
    firstName: v().required()
});

#validateParams(validatorSetup: Object, filterSetup: Object)

Validates the incoming parameters based on the structure and validators given.

ctx.validateParams({
    firstName: v().required()
});

#validateQuery(validatorSetup: Object, filterSetup: Object)

Validates the incoming query string values based on the structure and validators given.

ctx.validateQuery({
    firstName: v().required()
});

#validateHeaders(validatorSetup: Object, filterSetup: Object)

Validates the incoming header values based on the structure and validators given.

ctx.validateHeaders({
    'x-my-token': v().required().uuid()
});

#validationErrors: Object

This is a variable that is set in the event of a failed validation. It is an object that contains keys and messages for the values that failed validation.

In the example below there is a top level property and an example of a response if an object of address and line1 is required.

Example JSON Response:

{
    "firstName": "Value is required.",
    "address.line1": "Value is required."
}