koa-protobuf
Version:
protobuf.js parser and sender middleware for koa
82 lines (58 loc) • 2.34 kB
Markdown
> [protobuf.js](https://github.com/dcodeIO/protobuf.js) parser and sender
> middleware for [koa](https://koajs.com).
[](https://travis-ci.com/bbridges/koa-protobuf)
[](https://coveralls.io/github/bbridges/koa-protobuf?branch=master)
[](https://www.npmjs.com/package/koa-protobuf)
*Note: koa v1.x is not supported.*
Install using `npm`:
```
$ npm install koa-protobuf
```
`koa-protobuf` ships with separate parser and sender middleware.
Because protobuf parsing requires the message type to be passed, it is
recommended to apply the parsing middleware directly to the individual routes
instead of using it globally.
Example usage with [`koa-router`](https://github.com/alexmingoia/koa-router):
```js
import Koa from 'koa';
import Router from 'koa-router';
import { protobufParser, protobufSender } from 'koa-protobuf';
// Messages generated by the protobuf.js cli.
import messages from './messages.js';
let app = new Koa();
let router = new Router();
// This will encode messages when ctx.proto is set.
app.use(protobufSender());
// Returns a protobuf message.
router.get('/api/example', (ctx) => {
ctx.proto = messages.ExampleMessage.create({
example_field: 'test'
});
});
// Accepts a protobuf as the content type. Clients should set their
// content-type to application/x-protobuf (or application/json when
// using compliant JSON). Otherwise, a 415 status code will be sent
// back and the next middleware will not run.
router.post('/api/example', protobufParser(messages.Example), (ctx) => {
console.log(ctx.request.proto);
});
app.use(router.routes());
app.use(router.allowedMethods());
```
Note that by default,
[](https://developers.google.com/protocol-buffers/docs/proto3#json)
can be received and sent. To disable this, set the `parseJson` and `sendJson`
options to `false`.
```js
app.use(sendProtobuf({ sendJson: false }));
router.post('/api/example', parseProtobuf(messages.Example, {
parseJson: false
}), (ctx) => {
// ...
});
```
Released under the MIT License (see `LICENSE`).