Coder Social home page Coder Social logo

egg-rpc-generator's Introduction

egg-rpc-generator

NPM version Test coverage npm download

RPC tools for egg framework

Install

$ npm i egg-rpc-generator -g

Usage

1. Command-line interface (cli) usage

$ egg-rpc-generator -h

  Usage: egg-rpc-generator [options]

  Options:

    -b, --base [base]            the base directory of the project
    -p, --plugin [plugin]        the plugins used in generation process
    -f, --framework [framework]  specify framework that can be absolute path or npm package
    -k, --keep-case              keeps field casing instead of converting to camel case
    -h, --help                   output usage information
  • -b, --base the egg project root folder, default is process.cwd()
  • -p, --plugin the plugins will be used in generation process, by default protobuf plugin will be activated
  • -f, --framework specify the custom egg framework name or path
  • -k, --keep-case keeps field casing instead of converting to camel case

run egg-rpc-generator under the egg project root folder

$ egg-rpc-generator

Create /home/admin/project proxy
[ProtoRPCPlugin] found "com.rpc.test.ProtoService" in proto file
[ProtoRPCPlugin] save all proto info into "/home/admin/project/run/proto.json"
------------------------------------------------
All done

2. Usage with package.json scripts

{
  "scripts": {
    "rpc": "egg-rpc-generator"
  }
}

Run arbitrary package scripts

$ npm run rpc

Create /home/admin/project proxy
[ProtoRPCPlugin] found "com.rpc.test.ProtoService" in proto file
[ProtoRPCPlugin] save all proto info into "/home/admin/project/run/proto.json"
------------------------------------------------
All done

Build-in Plugin

Protobuf Plugin

To generate rpc schema and proxy files from *.proto files

  • step 1: put your *.proto files into $base/proto folder
.
├── app
├── config
│   ├── config.default.js
│   └── proxy.js
├── package.json
└── proto
    └── ProtoService.proto

proto/ProtoService.proto

syntax = "proto3";

package com.alipay.sofa.rpc.test;

// 可选
option java_multiple_files = false;

service ProtoService {
  rpc echoObj (EchoRequest) returns (EchoResponse) {}
}

message EchoRequest {
  string name = 1;
  Group group = 2;
}

message EchoResponse {
  int32 code = 1;
  string message = 2;
}

enum Group {
  A = 0;
  B = 1;
}
  • step 2: config the config/proxy.js
module.exports = {
  group: 'SOFA',
  errorAsNull: false,
  services: [{
    appName: 'pb',
    responseTimeout: 100,
    api: {
      ProtoService: {
        interfaceName: 'com.alipay.sofa.rpc.test.ProtoService',
        version: '1.0',
        method: {
          echoObj: {
            responseTimeout: 3000,
          },
        },
      },
    },
  }],
};
  • step 3: run egg-rpc-generator under the project folder

will generate app/proxy/ProtoService.js and run/proto.json

.
├── app
│   └── proxy
│       └── ProtoService.js
├── config
│   ├── config.default.js
│   └── proxy.js
├── package.json
├── proto
│   └── ProtoService.proto
└── run
    └── proto.json

app/proxy/ProtoService.js

// Don't modified this file, it's auto created by egg-rpc-generator

'use strict';

const path = require('path');

/* eslint-disable */
/* istanbul ignore next */
module.exports = app => {
  const consumer = app.rpcClient.createConsumer({
    interfaceName: 'com.alipay.sofa.rpc.test.ProtoService',
    targetAppName: 'pb',
    version: '1.0',
    group: 'SOFA',
    proxyName: 'ProtoService',
    responseTimeout: 100,
  });

  if (!consumer) {
    // `app.config['pb.rpc.service.enable'] = false` will disable this consumer
    return;
  }

  app.beforeStart(async() => {
    await consumer.ready();
  });

  class ProtoService extends app.Proxy {
    constructor(ctx) {
      super(ctx, consumer);
    }

    async echoObj(req) {
      return await consumer.invoke('echoObj', [ req ], {
        ctx: this.ctx,
        responseTimeout: 3000,
      });
    }
  }

  return ProtoService;
};
/* eslint-enable */

Jar2Proxy Plugin

To generate rpc proxy from jar.

  • step 1: config config/proxy.js

Please refer to jar2proxy configuration for detail.

  • step 2: put jar file into $app_root/assembly folder
.
├── app
├── assembly
│   ├── dubbo-demo-api-1.0-SNAPSHOT-sources.jar
│   ├── dubbo-demo-api-1.0-SNAPSHOT.jar
│   ├── jar2proxy-facade-1.0.0-sources.jar
│   └── jar2proxy-facade-1.0.0.jar
├── config
│   └── proxy.js
└── package.json
  • step 3: run egg-rpc-generator under the project folder

will generate following folders:

  • app/proxy all proxy files.
  • app/proxy_class all class definitions
  • app/proxy_enums all enums definitions

Jsdoc2Jar

To generator jave interface definitions(jars) from JavaScript comments.

  • step 1: config config/config.default.js
exports.rpc = {
  server: {
    namespace: 'com.eggjs.xxx',
    // group: 'xxx',
    // version: '1.0.0',
    // pom: {
    //   version: '1.0.0',
    //   groupId: 'com.eggjs.facade',
    //   artifactId: 'your-artifactId',
    // },
  },
};
  • step 2: write rpc service with js comments
// $app_root/rpc/HelloService.js

/**
 * say hello
 * @param {String} name - user name
 * @return {String} hello words
 * @rpc
 */
exports.sayHello = async function (name) {
  return 'hello ' + name;
};
  • step 3: run egg-rpc-generator under the project folder

will generate:

  • $app_root/src: java interface definitions source code
  • $app_root/target: the output of mvn clean install

Write Your Plugin

You can write your own egg-rpc-generator plugin.

  • Write a plugin, and publish it to NPM.
module.exports = async (units, { baseDir }) => {
  // do something
};
  • Use plugin:

install plugin from NPM, then use it with egg-rpc-generator:

$ egg-rpc-generator -p pluginName1,pluginName2,...

License

MIT

Contributors


gxcsoccer


zhoukk

This project follows the git-contributor spec, auto updated at Fri Jun 16 2023 21:14:08 GMT+0800.

egg-rpc-generator's People

Contributors

fengmk2 avatar gxcsoccer avatar semantic-release-bot avatar zhoukk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

egg-rpc-generator's Issues

生成的proxy文件的group参数无法为null

proxy.js:

    module.exports = {
    version: '1.0.0',
    group: null,

proxy/xxx.js

module.exports = function (app) {
  const appName = 'xxx';
  let version = '1.0.0';
  if (app.config.proxy && app.config.proxy.envVersion) {
    version = app.config.proxy.envVersion[appName] || version;
  }
  const rpcClient = app.rpcClient;
  if (!rpcClient) return;
  const consumer = rpcClient.createConsumer({
    interfaceName: 'xxx',
    version,
    targetAppName: appName,
    group: 'HSF',
    proxyName: 'activityServiceFacade',
    responseTimeout: 3000,
  });

配置为null或''时生成的是默认的'HSF'

npm run rpc后报错

PluginSequencifyError: sequencify plugins has problem, missing: [rpc], recursive: []
>> Plugin [rpc] is disabled or missed, but is required by [sofaRpc]

egg-soft-rpc ts 项目不能用生成的.js文件吗

我是用 -ts 文件模式, 调用 egg-rpc-generator 生成 ProtoService.js 文件,作为客户端, run dev 后启动报错, options.registry or options.serverHost at least set one 这句话什么意思?在package.json里面设置rpc吗?如果是,已经设置了

config.sofaRpc = {
    registry: {
      address: '127.0.0.1:2181', // 根据实际情况配置
    },
    client: {
      responseTimeout: 3000,
    },
  };

/Users/admin/Documents/Projects/moogrid-server-egg/puppeter/node_modules/[email protected]@sofa-rpc-node/lib/client/consumer.js:25
    assert(options.allowMock || options.serverHost || options.registry, '[RpcConsumer] options.registry or options.serverHost at least set one');
    ^
AssertionError [ERR_ASSERTION]: [RpcConsumer] options.registry or options.serverHost at least set one
    at new RpcConsumer (/Users/admin/Documents/Projects/moogrid-server-egg/puppeter/node_modules/[email protected]@sofa-rpc-node/lib/client/consumer.js:25:5)
    at EggRpcClient.createConsumer (/Users/admin/Documents/Projects/moogrid-server-egg/puppeter/node_modules/[email protected]@sofa-rpc-node/lib/client/client.js:97:18)
    at EggRpcClient.createConsumer (/Users/admin/Documents/Projects/moogrid-server-egg/puppeter/node_modules/[email protected]@egg-rpc-base/lib/client.js:41:18)
    at module.exports.app (/Users/admin/Documents/Projects/moogrid-server-egg/puppeter/app/proxy/ProtoService.js:10:34)
    at getExports (/Users/admin/Documents/Projects/moogrid-server-egg/puppeter/node_modules/[email protected]@egg-core/lib/loader/file_loader.js:220:15)
    at ContextLoader.parse (/Users/admin/Documents/Projects/moogrid-server-egg/puppeter/node_modules/[email protected]@egg-core/lib/loader/file_loader.js:158:25)
    at ContextLoader.load (/Users/admin/Documents/Projects/moogrid-server-egg/puppeter/node_modules/[email protected]@egg-core/lib/loader/file_loader.js:67:24)
    at AppWorkerLoader.loadToContext (/Users/admin/Documents/Projects/moogrid-server-egg/puppeter/node_modules/[email protected]@egg-core/lib/loader/egg_loader.js:408:28)
    at module.exports.app (/Users/admin/Documents/Projects/moogrid-server-egg/puppeter/node_modules/[email protected]@egg-rpc-base/app.js:7:14)
    at Hook.configDidLoad (/Users/admin/Documents/Projects/moogrid-server-egg/puppeter/node_modules/[email protected]@egg-core/lib/lifecycle.js:91:9)
[2020-05-14 07:41:42.611] [cfork:master:63327] worker:63352 disconnect (exitedAfterDisconnect: false, state: disconnected, isDead: false, worker.disableRefork: true)
[2020-05-14 07:41:42.612] [cfork:master:63327] don't fork, because worker:63352 will be kill soon
2020-05-14 07:41:42,613 INFO 63327 [master] app_worker#1:63352 disconnect, suicide: false, state: disconnected, current workers: ["1"]
[2020-05-14 07:41:42.613] [cfork:master:63327] worker:63352 exit (code: 1, exitedAfterDisconnect: false, state: dead, isDead: true, isExpected: false, worker.disableRefork: true)

上线部署egg.js后端 报nodejs.AssertionError: [RpcConsumer] options.registry or options.serverHost at least set one

在本地测试的好好的,业务开发完,上线部署,输入:npm start,甚至npm run dev也不行。是egg-rpc-generator的问题吗?
报:
2022-05-25 10:26:34,986 ERROR 26361 nodejs.AssertionError: [RpcConsumer] options.registry or options.serverHost at least set one
at new RpcConsumer (/www/wwwroot/mallapi.carsmaga.com/node_modules/sofa-rpc-node/lib/client/consumer.js:25:5)
at EggRpcClient.createConsumer (/www/wwwroot/mallapi.carsmaga.com/node_modules/sofa-rpc-node/lib/client/client.js:97:18)
at EggRpcClient.createConsumer (/www/wwwroot/mallapi.carsmaga.com/node_modules/egg-rpc-base/lib/client.js:41:18)
at module.exports (/www/wwwroot/mallapi.carsmaga.com/app/proxy/userService.js:17:30)
at getExports (/www/wwwroot/mallapi.carsmaga.com/node_modules/egg-core/lib/loader/file_loader.js:220:15)
at ContextLoader.parse (/www/wwwroot/mallapi.carsmaga.com/node_modules/egg-core/lib/loader/file_loader.js:158:25)
at ContextLoader.load (/www/wwwroot/mallapi.carsmaga.com/node_modules/egg-core/lib/loader/file_loader.js:67:24)
at AppWorkerLoader.loadToContext (/www/wwwroot/mallapi.carsmaga.com/node_modules/egg-core/lib/loader/egg_loader.js:408:28)
at module.exports (/www/wwwroot/mallapi.carsmaga.com/node_modules/egg-rpc-base/app.js:7:14)
at Hook.configDidLoad (/www/wwwroot/mallapi.carsmaga.com/node_modules/egg-core/lib/lifecycle.js:91:9)
generatedMessage: false
code: "ERR_ASSERTION"
actual: null
expected: true
operator: "=="
pid: 26361
hostname: VM-64-14-centos

/www/wwwroot/mallapi.carsmaga.com/node_modules/egg-cluster/lib/app_worker.js:26
throw err;

执行egg-rpc-generator会去构建maven项目进而引发错误,不能退出

在执行egg-rpc-generator时,因为这个项目是纯客户端执行没问题,服务端执行就会去构建maven项目,我不知道这个是不是开发忘记删除什么东西了,因为即使构建失败也不会影响项目运行,但是构建失败会产生错误,这个错误会被捕捉到,问题就在于egg-rpc-generator.js文件中的这句代码console.error(err.stack.red);因为err.stack是undefined的,所以会导致process无法退出,希望能够修改一下,虽然好像这个项目没人维护了

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.