Skip to content
This repository has been archived by the owner on Jan 29, 2018. It is now read-only.

feat(main): RPC Router and Server implementation #1

Merged
merged 1 commit into from
Nov 13, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
Node module: loopback4-example-rpc-server
This project is licensed under the MIT License, full text below.

--------

MIT license

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,30 @@ An example RPC server and application to demonstrate the creation of your
own custom server.

[![LoopBack](http://loopback.io/images/overview/powered-by-LB-xs.png)](http://loopback.io/)

## Usage
Install dependencies and start the app:
```sh
npm install
npm start
```

Next, use your favourite REST client to send RPC payloads to the server
(hosted on port 3000).

## Request Format

The request body should contain a controller name, method name and input object.
Example:
```json
{
"controller": "GreetController",
"method": "basicHello",
"input": {
"name": "Janet"
}
}
```
The router will determine which controller and method will service your request
based on the given names in the payload.

11 changes: 11 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Copyright IBM Corp. 2017. All Rights Reserved.
// Node module: loopback4-example-rpc-server
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

// NOTE(bajtos) This file is used by TypeScript compiler to resolve imports
// from "test" files against original TypeScript sources in "src" directory.
// As a side effect, `tsc` also produces "dist/index.{js,d.ts,map} files
// that allow test files to import paths pointing to {src,test} root directory,
// which is project root for TS sources but "dist" for transpiled sources.
export * from './src';
48 changes: 48 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"name": "loopback4-example-rpc-server",
"version": "1.0.0",
"description": "A basic RPC server using a made-up protocol.",
"keywords": ["loopback-application", "loopback"],
"main": "index.js",
"engines": {
"node": ">=8"
},
"scripts": {
"build": "lb-tsc",
"build:watch": "lb-tsc --watch",
"clean": "lb-clean",
"lint": "npm run prettier:check && npm run tslint",
"lint:fix": "npm run prettier:fix && npm run tslint:fix",
"prettier:cli": "lb-prettier \"**/*.ts\"",
"prettier:check": "npm run prettier:cli -- -l",
"prettier:fix": "npm run prettier:cli -- --write",
"tslint": "lb-tslint",
"tslint:fix": "npm run tslint -- --fix",
"pretest": "npm run clean && npm run build",
"test": "lb-dist mocha DIST/test",
"posttest": "npm run lint",
"start": "npm run build && node .",
"prepare": "npm run build"
},
"repository": {
"type": "git"
},
"author": "",
"license": "MIT",
"files": ["README.md", "index.js", "index.d.ts", "dist", "dist6"],
"dependencies": {
"@loopback/context": "^4.0.0-alpha.18",
"@loopback/core": "^4.0.0-alpha.20",
"@types/express": "^4.0.39",
"@types/node": "^8.0.51",
"@types/p-event": "^1.3.0",
"express": "^4.16.2",
"p-event": "^1.3.0"
},
"devDependencies": {
"@loopback/build": "^4.0.0-alpha.5",
"@loopback/testlab": "^4.0.0-alpha.13",
"@types/mocha": "^2.2.43",
"mocha": "^4.0.1"
}
}
21 changes: 21 additions & 0 deletions src/application.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {Application, ApplicationConfig} from '@loopback/core';
import {RPCServer} from './servers/rpc-server';
import {GreetController} from './controllers';

export class MyApplication extends Application {
options: ApplicationConfig;
constructor(options?: ApplicationConfig) {
// Allow options to replace the defined components array, if desired.
super(options);
this.controller(GreetController);
this.server(RPCServer);
this.options = options || {};
this.options.port = this.options.port || 3000;
this.bind('rpcServer.config').to(this.options);
}

async start() {
await super.start();
console.log(`Server is running on port ${this.options.port}`);
}
}
13 changes: 13 additions & 0 deletions src/controllers/greet.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {Person} from '../models';

export class GreetController {
basicHello(input: Person) {
return `Hello, ${(input && input.name) || 'World'}!`;
}

hobbyHello(input: Person) {
return `${this.basicHello(input)} I heard you like ${(input &&
input.hobby) ||
'underwater basket weaving'}.`;
}
}
1 change: 1 addition & 0 deletions src/controllers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './greet.controller';
18 changes: 18 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright IBM Corp. 2017. All Rights Reserved.
// Node module: some-project
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {MyApplication} from './application';
import {ApplicationConfig} from '@loopback/core';

export async function main(options?: ApplicationConfig) {
const app = new MyApplication(options);

try {
await app.start();
} catch (err) {
console.error(`Unable to start application: ${err}`);
}
return app;
}
1 change: 1 addition & 0 deletions src/models/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './person.model';
5 changes: 5 additions & 0 deletions src/models/person.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Note that this can also be a class!
export type Person = {
name?: string;
hobby?: string;
};
2 changes: 2 additions & 0 deletions src/servers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './rpc-router';
export * from './rpc-server';
52 changes: 52 additions & 0 deletions src/servers/rpc-router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import {RPCServer} from './rpc-server';
import * as express from 'express';
import * as parser from 'body-parser';

export class RPCRouter {
routing: express.Router;
constructor(private server: RPCServer) {
this.routing = express.Router();
const jsonParser = parser.json();
this.routing.post('*', jsonParser, (request, response) => {});
if (this.server.expressServer) {
this.server.expressServer.use(this.routing);
}
}

async routeRequest(request: express.Request, response: express.Response) {
const ctrl = request.body.controller;
const method = request.body.method;
const input = request.body.input;
let controller;
try {
controller = await this.getController(ctrl);
if (!controller[method]) {
throw new Error(
`No method was found on controller "${ctrl}" with name "${method}".`,
);
}
} catch (err) {
this.sendErrResponse(response, err, 400);
return;
}
try {
response.send(await controller[method](input));
} catch (err) {
this.sendErrResponse(response, err, 500);
}
}

// tslint:disable-next-line:no-any
sendErrResponse(resp: express.Response, send: any, statusCode: number) {
resp.statusCode = statusCode;
resp.send(send);
}

async getController(ctrl: string): Promise<Controller> {
return (await this.server.get(`controllers.${ctrl}`)) as Controller;
}
}

export type Controller = {
[method: string]: Function;
};
38 changes: 38 additions & 0 deletions src/servers/rpc-server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import {inject, Context} from '@loopback/context';
import {Server, Application, CoreBindings} from '@loopback/core';
import {RPCRouter} from './rpc-router';
import * as express from 'express';
import * as http from 'http';
import * as pEvent from 'p-event';

export class RPCServer extends Context implements Server {
_server: http.Server;
expressServer: express.Application;
router: RPCRouter;
constructor(
@inject(CoreBindings.APPLICATION_INSTANCE) public app?: Application,
@inject('rpcServer.config') public config?: RPCServerConfig,
) {
super(app);
this.config = config || {};
}

async start(): Promise<void> {
this.expressServer = express();
this.router = new RPCRouter(this);
this._server = this.expressServer.listen(
(this.config && this.config.port) || 3000,
);
return await pEvent(this._server, 'listening');
}
async stop(): Promise<void> {
this._server.close();
return await pEvent(this._server, 'close');
}
}

export type RPCServerConfig = {
port?: number;
// tslint:disable-next-line:no-any
[key: string]: any;
};
4 changes: 4 additions & 0 deletions test/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Tests

Please place your tests in this folder.

40 changes: 40 additions & 0 deletions test/controllers/greet.controller.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import 'mocha';
import {GreetController} from '../../src/controllers';
import {expect} from '@loopback/testlab';

describe('greet.controller', () => {
const controller = new GreetController();
describe('basicHello', () => {
it('returns greetings for a name', () => {
expect(controller.basicHello({})).to.equal('Hello, World!');
});

it('returns greetings for the world without valid input', () => {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it('returns greetings with valid input, ...

const input = {
name: 'Aaron',
};
const expected = `Hello, ${input.name}!`;
expect(controller.basicHello(input)).to.equal(expected);
});
});
describe('hobbyHello', () => {
it('returns greetings for a name', () => {
const input = {
name: 'Aaron',
};
expect(controller.hobbyHello(input)).to.match(
/Hello, Aaron!(.*)underwater basket weaving/,
);
});

it('returns greetings for a name and hobby', () => {
const input = {
name: 'Aaron',
hobby: 'sportsball',
};
expect(controller.hobbyHello(input)).to.match(
/Hello, Aaron!(.*)sportsball/,
);
});
});
});
1 change: 1 addition & 0 deletions test/mocha.opts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
--recursive
Loading