koa-respond
Middleware for Koa that adds useful methods to the Koa context.
Installation
npm install --save koa-respond
Usage
// Install itconst respond = ; // For Koa v2 - if you are looking for v1, scroll to the bottom.app; // Use itapp;
Methods
All methods call the send
method with the corresponding status code as well as the body. That means they support the same overloads as send
:
-
With a string; wraps it in an object with a
message
property. That means the following 2 calls do the same thing:ctx;ctx; -
With an object; sends the object as JSON.
ctx;
If you wish to disable the automatic wrapping of strings globally, you can instantiate koa-respond
with autoMessage: false
.
app
All functions return the Koa context itself (chainable)
ctx
All functions are also bound to the context. This means you can pass the function as a reference without having to bind it first.
app
Available methods
ok
-HTTP 200
created
-HTTP 201
noContent
-HTTP 204
- always sends an empty response!badRequest
-HTTP 400
unauthorized
-HTTP 401
forbidden
-HTTP 403
notFound
-HTTP 404
internalServerError
-HTTP 500
Does this work for Koa 1?
Not out of the box, because it's time you move on to v2.
To use koa-respond
in Koa v1, you need to patch the context yourself. This is what the v2 middleware does.
const respond = ; // Middleware to install koa-respond.app; // Now the methods are available.app;
Adding additional methods
If you feel like some methods are missing, you can add them yourself, like so:
app; app;
Even more custom methods
If you just want to add shortcuts without adding an additional middleware, you can do that, too.
app; app;
Contributing
npm run
scripts
npm run test
: Runs tests oncenpm run test-watch
: Runs tests in watch-modenpm run lint
: Lints the code oncenpm run lint-watch
: Lints the code in watch-modenpm run cover
: Runs code coverage usingistanbul
npm run coveralls
: Used by coveralls
Author
Jeff Hansen - @Jeffijoe