koa-grpc
v1.0.6
Published
The grpc middle of Koa.
Downloads
99
Readme
koa-grpc
The grpc middle of Koa, foundation for koaland
Installation
npm i koa-grpc -S
Usage
simple app
import { Context } from 'koa';
import KoaGrpc from 'koa-grpc';
var { GreeterService } = require('./gen_code/helloworld_grpc_pb');
const app = new KoaGrpc({ service: GreeterService });
// not found
app.use((ctx: Context) => {
console.log('ctx.request: ', (ctx.request as any).getName());
});
// result -> Error: 12 UNIMPLEMENTED: Not Found
app.listen('0.0.0.0:50051');
console.log('listening on 50051...');
with route
import { Context } from 'koa';
import KoaGrpc from 'koa-grpc';
const mount = require('koa-mount');
var { GreeterService } = require('./gen_code/helloworld_grpc_pb');
var messages = require('./gen_code/helloworld_pb');
const app = new KoaGrpc({ service: GreeterService });
// with route
app.use(
mount('/sayHello', function (ctx: Context) {
console.log('ctx.request: ', (ctx.request as any).getName());
var reply = new messages.HelloReply();
reply.setMessage('Hello ' + ctx.call.request.getName());
ctx.body = reply;
})
);
app.listen('0.0.0.0:50051');
console.log('listening on 50051...');
use middleware
import { Context } from 'koa';
import KoaGrpc from 'koa-grpc';
const mount = require('koa-mount');
var { GreeterService } = require('./gen_code/helloworld_grpc_pb');
var messages = require('./gen_code/helloworld_pb');
const app = new KoaGrpc({ service: GreeterService });
// use middleware
app.use(async (ctx, next) => {
const start = Date.now();
await next();
console.log(`process ${ctx.path} request from ${ctx.ip} cost ${Date.now() - start}ms`);
});
// with route
app.use(
mount('/sayHello', async function (ctx: Context) {
console.log('ctx.request: ', (ctx.request as any).getName());
var reply = new messages.HelloReply();
reply.setMessage('Hello ' + ctx.call.request.getName());
await sleep(300); // wait sth
ctx.body = reply;
})
);
app.listen('0.0.0.0:50051');
console.log('listening on 50051...');
function sleep(delay = 1000) {
return new Promise((resolve) => setTimeout(resolve, delay));
}
Generate code
npm install -g grpc-tools
cd ./examples
grpc_tools_node_protoc --js_out=import_style=commonjs,binary:./gen_code --grpc_out=grpc_js:./gen_code helloworld.proto
Examples
examples with client are listed at examples
Others
more node.js examples from official
License
MIT