项目作者: mhingston

项目描述 :
JSON-RPC server over WebSockets
高级语言: JavaScript
项目地址: git://github.com/mhingston/respect.git
创建时间: 2017-09-29T22:03:02Z
项目社区:https://github.com/mhingston/respect

开源协议:MIT License

下载


ResPeCt

JSON-RPC 2.0 server over WebSockets.

For a JSON-RPC 2.0 client check out CyPRus.

UPDATE (2018-15-02): Deprecated in favour of Jayson.

Installation

  1. npm install mhingston/respect

Usage

  1. // Import the module
  2. const Respect = require('respect');
  3. // Declare an object literal with all the methods you want to expose...
  4. const methods =
  5. {
  6. foo: () => 'hello',
  7. bar: (a, b) => a + b,
  8. baz: ({name}) => 'hello ' + name
  9. };
  10. // ...or pass in an instance of a class with the methods you want to expose.
  11. class Method
  12. {
  13. foo()
  14. {
  15. return 'hello';
  16. }
  17. bar(a, b)
  18. {
  19. return a + b
  20. }
  21. baz({name})
  22. {
  23. return 'hello ' + name;
  24. }
  25. }
  26. const methods = new Method();

You can optionally include a schema object within methods for defining JSON schemas for methods which expect named (i.e. destructured) parameters.

  1. methods.schema =
  2. {
  3. baz:
  4. {
  5. properties:
  6. {
  7. name:
  8. {
  9. type: 'string'
  10. }
  11. },
  12. minProperties: 1,
  13. additionalProperties: false
  14. }
  15. }

Define your config:

  1. const config =
  2. {
  3. instance: methods,
  4. logger: true,
  5. wsOptions:
  6. {
  7. port: 33333
  8. }
  9. }
  • instance {Object} Object containing the methods exposed to the RPC server.
  • logger {Boolean|Function} Set to true to have debug log written to the console or pass a function to receive the log messages. Default = false.
  • wsOptions {Object} Options passed to ws.

Instantiate a new RPC server

  1. const rpc = new Respect(config);

Notes

  • Supports JSON-RPC 2.0 only.
  • Calls to methods without named parameters must have the same number of arguments as the method signature.
  • Supports async methods, i.e. returning a promise. Callbacks are not supported as functions don’t “JSONify”.
  • You can access the client headers sent with the upgrade request from within a method by accessing the property <methodName>._requestHeaders or this._requestHeaders depending on whether your method has a lexical this.
  • Check out the tests for more examples.