• Stars
    star
    102
  • Rank 324,472 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 8 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Koa middleware that adds useful methods to the context.

koa-respond

npm dependency Status devDependency Status Build Status Coveralls Code Climate npm license node JavaScript Style Guide KoaJs Slack

Middleware for Koa that adds useful methods to the Koa context.

Installation

npm install --save koa-respond

Usage

// Install it
const respond = require('koa-respond');

// For Koa v2 - if you are looking for v1, scroll to the bottom.
app.use(respond());

// Use it
app.use((ctx) => {
  // Sets status to 200 and the body to `{ id: 123, name: 'Dat Boi' }`
  ctx.ok({ id: 123, name: 'Dat Boi' });

  // Both of these set status to 404 and
  // the body to `{ message: 'Not found, boii' }`
  ctx.notFound('Not found, boii');
  ctx.notFound({ message: 'Not found, boii' });

  // And everyone's favorite..
  ctx.badRequest({ error: 'missing input' });

  // Or if you prefer to do it yourself..
  // Both of these send a HTTP 201 with a body
  // of `{ message: 'new beginnings!' }`
  ctx.send(201, 'new beginnings!');
  ctx.send(201, { message: 'new beginnings!' });
});

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.send(400, 'lol no');
    ctx.send(400, { message: 'lol no' });
  • With an object; sends the object as JSON.

    ctx.send(200, { id: 123, name: 'new entity' });

If you wish to disable the automatic wrapping of strings globally, you can instantiate koa-respond with autoMessage: false.

app.use(respond({
  autoMessage: false
}))

All functions return the Koa context itself (chainable)

ctx.ok().set({ 'X-Some-Header': 'awesome' })

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.use((ctx) => somePromiseCall().then(ctx.ok))

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
  • locked - HTTP 423
  • internalServerError - HTTP 500
  • notImplemented - HTTP 501

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 = require('koa-respond');

// Middleware to install koa-respond.
app.use(function *(next) {
  respond().patch(this);
  yield next;
});

// Now the methods are available.
app.use(function *() {
  this.ok({ id: 123, name: 'Bob' });
});

Adding additional methods

If you feel like some methods are missing, you can add them yourself, like so:

app.use(respond({
  statusMethods: {
    imATeapot: 418,
    enhanceYourCalm: 420
  }
}));

app.use((ctx) => {
  ctx.imATeapot('Hello, a Teapot I am.');
  ctx.enhanceYourCalm({ todo: 'blaze it' });
});

Even more custom methods

If you just want to add shortcuts without adding an additional middleware, you can do that, too.

app.use(respond({
  methods: {
    shizzle: (ctx, message) => {
      ctx.send(200, message + ', fo-shizzle');
    }
  }
}));

app.use((ctx) => {
  // HTTP 200 { message: 'Koa is the best, fo-shizzle' }
  ctx.shizzle('Koa is the best');
});

Contributing

npm run scripts

  • npm run test: Runs tests once
  • npm run test-watch: Runs tests in watch-mode
  • npm run lint: Lints the code once
  • npm run lint-watch: Lints the code in watch-mode
  • npm run cover: Runs code coverage using istanbul
  • npm run coveralls: Used by coveralls

Author

Jeff Hansen - @Jeffijoe

More Repositories

1

awilix

Extremely powerful Inversion of Control (IoC) container for Node.JS
TypeScript
2,999
star
2

typesync

Install missing TypeScript typings for dependencies in your package.json.
TypeScript
1,390
star
3

koa-es7-boilerplate

A boilerplate for writing Koa 2 apps in ES7 with Babel.
JavaScript
274
star
4

mobx-task

Makes async function state management in MobX fun.
TypeScript
237
star
5

messageformat.net

ICU MessageFormat implementation for .NET.
C#
148
star
6

awilix-koa

Awilix helpers/middleware for Koa 2
TypeScript
129
star
7

yenv

Environment management for Node using YAML.
JavaScript
104
star
8

awilix-express

Awilix helpers/middleware for Express
TypeScript
101
star
9

libx

Collection + Model infrastructure for MobX applications.
TypeScript
99
star
10

httpclientgoodies.net

Useful utilities for the .NET HttpClient.
C#
62
star
11

snicket

Stream Store based on Postgres for Node.JS
TypeScript
39
star
12

screengun

A simple screen recorder for Windows based on ffmpeg
C#
39
star
13

fejl

Error-making utility for Node apps.
TypeScript
35
star
14

logpipe-server

The Logpipe server.
JavaScript
30
star
15

awilix-router-core

Reusable building blocks for writing Awilix router adapters for HTTP frameworks.
TypeScript
25
star
16

validx

Validation library for MobX.
TypeScript
23
star
17

keyblade

Fail fast when accessing undefined properties on objects.
JavaScript
14
star
18

npm-module-boilerplate

A boilerplate for authoring npm modules, with tests and linting.
JavaScript
10
star
19

skadi

A simple object validator/sanitizer based on `is-my-json-valid`.
JavaScript
9
star
20

deltio

A Google Cloud Pub/Sub emulator alternative, written in Rust.
Rust
8
star
21

dration

Duration utilities for JavaScript using primitive types.
TypeScript
6
star
22

icebug

A wrapper around node-inspector and nodemon.
JavaScript
4
star
23

jQuery-Validator.Knockout

KnockoutJS bindings for my jQuery-Validator.
JavaScript
4
star
24

bristol-sentry

Sentry integration for the Bristol logger
JavaScript
3
star
25

smid

Catches errors and returns them. Useful for unit testing.
TypeScript
3
star
26

baconpi-web

BaconPi Web Frontend + Backend
JavaScript
3
star
27

ts-module-boilerplate

TypeScript module boilerplate for Node packages
TypeScript
3
star
28

posish

A tool that makes counting string lines, columns and indexes awesome. Useful for writing parser tests.
JavaScript
2
star
29

total-rename

Utility to replace strings in files and paths.
Go
2
star
30

purge

Windows utility for deleting a directory tree with long paths.
C#
1
star
31

chilli

Rename files to sort-friendly numbers
F#
1
star
32

jQuery-Validator

A formless validation plugin for all kinds of validation - even your own!
JavaScript
1
star