koa-protobuf

protobuf.js parser and sender middleware for koa

Usage no npm install needed!

<script type="module">
  import koaProtobuf from 'https://cdn.skypack.dev/koa-protobuf';
</script>

README

koa-protobuf

protobuf.js parser and sender middleware for koa.

Build Status Test Coverage NPM Version

Note: koa v1.x is not supported.

Installation

Install using npm:

$ npm install koa-protobuf

Usage

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:

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, protobuf-compliant JSON can be received and sent. To disable this, set the parseJson and sendJson options to false.

app.use(sendProtobuf({ sendJson: false }));

router.post('/api/example', parseProtobuf(messages.Example, {
  parseJson: false
}), (ctx) => {
  // ...
});

License

Released under the MIT License (see LICENSE).