rpc-controllers
Allows to create controller classes with methods as JSON-RPC methods that handle JSON-RPC 2.0 requests. You can use rpc-controllers with express.js or koa.js.
Table of contents
Installation
-
Install module:
npm install rpc-controllers --save
-
reflect-metadata
shim is required:npm install reflect-metadata --save
and make sure to import it before you use rpc-controllers:
; -
Install framework:
a. If you want to use rpc-controllers with express.js, then install it and all required dependencies:
npm install express body-parser --save
Optionally you can also install their typings:
npm install @types/express @types/body-parser --save
b. If you want to use rpc-controllers with koa.js, then install it and all required dependencies:
npm install koa koa-router koa-bodyparser --save
Optionally you can also install their typings:
npm install @types/koa @types/koa-router @types/koa-bodyparser --save
-
Its important to set these options in
tsconfig.json
file of your project:
Example of usage
-
Create a file
MathController.ts
;@@return params;@return params;This class will register JSON-PRC methods specified in method decorators in your server framework (express.js or koa).
-
Create a file
app.ts
; // don't forget import this shim!;;// creates express app, registers all controller methods and returns you express app instanceconst app =;// run express application on port 3000app;if you are koa user you just need to use
createKoaServer
instead ofcreateExpressServer
-
Send a JSON-RPC 2.0 request to
http://localhost:3000
using the methodmath.add
and the params[1, 1]
. You will get the result2
.
More usage examples
Load all controllers from the given directory
; // don't forget import this shim!; const app = ; // run express application on port 3000app;
Pre-configure express/koa
If you have, or if you want to create and configure express app separately,
you can use useExpressServer
instead of createExpressServer
function:
;;; let express = ; // or you can import it if you have installed typingslet app = ; // your created express server// app.use() // you can configure it the way you want;app; // run your express server
Using DI container
rpc-controllers
supports a DI container out of the box.
You can inject your services into your controllers. Container must be setup during application bootstrap.
Here is example how to integrate rpc-controllers with typedi:
;;; // its important to set container before any operation you do with rpc-controllers,// including importing controllers; // create and run express serverlet app = ;
That's it, now you can inject your services into your controllers:
@ { } // ... controller methods