Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new package for rsocket gateway client #284

Closed
wants to merge 6 commits into from
Closed
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
7 changes: 7 additions & 0 deletions packages/rsocket-ws-gateway-client/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.cache
node_modules

lib/
es/

report.html
22 changes: 22 additions & 0 deletions packages/rsocket-ws-gateway-client/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[![Join the chat at https://gitter.im/scalecube-js/Lobby](https://badges.gitter.im/scalecube-js/Lobby.svg)](https://gitter.im/scalecube-js/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

> This is part of [scalecube-js](https://github.com/scalecube/scalecube-js) project, see more at <https://github.com/scalecube/scalecube-js>
> [Full documentation](http://scalecube.io/javascript-docs)

# rsocket-websocket-gateway-client

Client for rsocket websocket gateway for browser and server usage

```typescript
import { createGatewayProxy } from '@scalecube/rsocket-ws-gateway-client';


const definition = {
serviceName: 'serviceA',
methods: {
methodA: { asyncModel: ASYNC_MODEL_TYPES.REQUEST_RESPONSE },
},
};
const proxy = await createGatewayProxy('ws://localhost:3000', definition);
const resp = await proxy.methodA() // => 'ok'
```
9 changes: 9 additions & 0 deletions packages/rsocket-ws-gateway-client/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = {
transform: {
'.(ts|tsx)': 'ts-jest',
},
testRegex: '(\\.|/)(test|spec)\\.ts$',
testPathIgnorePatterns: ['<rootDir>/es/', '<rootDir>/lib/', '<rootDir>/node_modules/'],
moduleFileExtensions: ['ts', 'tsx', 'js'],
moduleDirectories: ['node_modules', 'app/src'],
};
43 changes: 43 additions & 0 deletions packages/rsocket-ws-gateway-client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"name": "@scalecube/rsocket-ws-gateway-client",
"version": "0.2.9",
"private": false,
"main": "lib/index.js",
"types": "lib/index.d.ts",
"unpkg": "dist/index.js",
"files": [
"lib",
"dist"
],
"license": "MIT",
"scripts": {
"clean": "rimraf node_modules && rimraf .cache && rimraf lib",
"build": "rimraf .cache && yarn build:dist && yarn build:cjs",
"build:dist": "rimraf dist && rollup -c rollup.iife.config.js",
"build:cjs": "rimraf lib && rollup -c rollup.cjs.config.js",
"lint": "tslint '{src,tests}/**/*.{ts,tsx}' --fix",
"prettier": "prettier --write '{src,tests}/**/*.{ts,tsx}'",
"test": "jest --config jest.config.js",
"coverage": "yarn test --coverage --collectCoverageFrom='src/**/*.**' --collectCoverageFrom='!tests/**/*.**'"
},
"author": "Scalecube (https://github.com/scalecube/scalecube-js)",
"devDependencies": {
"jest": "^24.6.0",
"rollup": "^1.14.6",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-commonjs": "^10.0.1",
"rollup-plugin-filesize": "^6.1.1",
"rollup-plugin-typescript2": "^0.21.1",
"rollup-plugin-visualizer": "^2.2.0",
"ts-jest": "^24.2.0",
"tslint": "^5.11.0",
"typescript": "^3.2.4"
},
"dependencies": {
"@scalecube/utils": "^0.2.9",
"rsocket-core": "^0.0.16",
"rsocket-flowable": "^0.0.14",
"rsocket-websocket-client": "^0.0.16",
"ws": ">=3.3.1"
}
}
59 changes: 59 additions & 0 deletions packages/rsocket-ws-gateway-client/rollup.cjs.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import visualizer from 'rollup-plugin-visualizer';
import typescript from 'rollup-plugin-typescript2';
import tscompile from 'typescript';
import filesize from 'rollup-plugin-filesize';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import pkg from './package.json';
import babel from 'rollup-plugin-babel';

export default {
input: 'src/index.ts',
output: [
{
file: pkg.main,
format: 'cjs',
sourcemap: false,
},
],
external: ['rxjs'],
plugins: [
commonjs({
include: /node_modules/,
browser: true,
namedExports: {
'rsocket-types': ['CONNECTION_STATUS'],
},
}),
resolve(),
babel({
plugins: ['@babel/plugin-transform-arrow-functions'],
babelrc: false,
runtimeHelpers: true,
presets: [
[
'@babel/preset-env',
{
modules: false,
spec: true,
forceAllTransforms: true,
targets: {
chrome: '29',
ie: '11',
},
},
],
],
}),
visualizer({
filename: 'report.cjs.html',
title: 'Browser - cjs',
}),
typescript({
typescript: tscompile,
clean: true,
}),
// global(),
filesize(),
],
};
61 changes: 61 additions & 0 deletions packages/rsocket-ws-gateway-client/rollup.iife.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import visualizer from 'rollup-plugin-visualizer';
import typescript from 'rollup-plugin-typescript2';
import tscompile from 'typescript';
import filesize from 'rollup-plugin-filesize';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import pkg from './package.json';
import replace from 'rollup-plugin-replace';
import { terser } from 'rollup-plugin-terser';
import babel from 'rollup-plugin-babel';

export default {
input: 'src/index.ts',
output: [
{
name: 'sc',
file: pkg.unpkg,
format: 'iife',
sourcemap: false,
},
],
plugins: [
commonjs({
include: /node_modules/,
browser: true,
}),
resolve(),
babel({
plugins: ['@babel/plugin-transform-arrow-functions'],
babelrc: true,
runtimeHelpers: true,
presets: [
[
'@babel/preset-env',
{
modules: false,
spec: true,
forceAllTransforms: true,
targets: {
chrome: '29',
ie: '11',
},
},
],
],
}),
replace({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
visualizer({
filename: 'report.iffe.html',
title: 'Microservice - iife',
}),
typescript({
typescript: tscompile,
clean: true,
}),
terser(),
filesize(),
],
};
151 changes: 151 additions & 0 deletions packages/rsocket-ws-gateway-client/src/createGatewayProxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { Observable } from 'rxjs';
import RSocketWebSocketClient from 'rsocket-websocket-client';
import { RSocketClient, JsonSerializers } from 'rsocket-core';
import { MicroserviceApi } from '@scalecube/api';
import { validateServiceDefinition, getQualifier } from '@scalecube/utils';

interface Proxy {
[state: string]: any;
}

type ConnectionOptions = Partial<{
keepAlive: number;
lifetime: number;
}>;

export function createGatewayProxy(
url: string,
definition: MicroserviceApi.ServiceDefinition,
requestResponse?: any,
requestStream?: any,
options?: ConnectionOptions
): Promise<Proxy>;
export function createGatewayProxy(
url: string,
definition: MicroserviceApi.ServiceDefinition[],
requestResponse?: any,
requestStream?: any,
options?: ConnectionOptions
): Promise<Proxy[]>;
export function createGatewayProxy(
url: string,
definitions: any,
customRequestResponse?: any,
customRequestStream?: any,
options?: ConnectionOptions
): any {
const isDefinitionsArray = Array.isArray(definitions);
let defs: MicroserviceApi.ServiceDefinition[];
if (!isDefinitionsArray) {
defs = [definitions];
} else {
defs = definitions;
}
const proxies: Proxy[] = [];
let socket;
return new Promise(async (resolve, reject) => {
socket = await connect(url, options).catch((e) => {
reject(e);
});

defs.forEach((definition) => {
const { serviceName, methods } = definition;
validateServiceDefinition(definition);
const proxy: Proxy = {};
Object.keys(methods).forEach((method) => {
const asyncModel = methods[method].asyncModel;
const qualifier = getQualifier({ serviceName, methodName: method });
proxy[method] = (() => {
switch (asyncModel) {
case 'requestResponse':
return customRequestResponse
? customRequestResponse(socket, qualifier)
: requestResponse(socket, qualifier);
case 'requestStream':
return customRequestStream ? customRequestStream(socket, qualifier) : requestStream(socket, qualifier);
default:
reject(new Error('Unknown asyncModel'));
}
})();
});
proxies.push(proxy);
});

resolve(isDefinitionsArray ? proxies : proxies[0]);
});
}

const connect = (url, options: ConnectionOptions = {}) => {
return new Promise((resolve, reject) => {
const client = new RSocketClient({
serializers: JsonSerializers,
setup: {
dataMimeType: 'application/json',
keepAlive: options.keepAlive || 100000,
lifetime: options.lifetime || 100000,
metadataMimeType: 'application/json',
},
transport: new RSocketWebSocketClient({ url }),
});
client.connect().subscribe({
onComplete: (socket: any) => {
// console.log('Connected to ' + url);
resolve(socket);
},
onError: (error: any) => {
// console.log('Err', error);
reject({ message: 'Connection error: ' + error.message });
},
});
});
};

const requestResponse = (socket, qualifier) => {
return (...args) => {
return new Promise((resolve, reject) => {
socket
.requestResponse({
data: {
qualifier,
data: args,
},
})
.subscribe({
onComplete: ({ data }) => {
resolve(data);
},
onError: (e: any) => {
reject(e);
},
});
});
};
};

const requestStream = (socket, qualifier) => {
return (...args) => {
return new Observable((observer) => {
socket
.requestStream({
data: {
qualifier,
data: args,
},
})
.subscribe({
onSubscribe(subscription) {
subscription.request(2147483647);
},
onNext: ({ data }) => {
observer.next(data);
},
onComplete: () => {
observer.complete();
},
onError: (e: any) => {
observer.error(e);
},
});
});
};
};
3 changes: 3 additions & 0 deletions packages/rsocket-ws-gateway-client/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { createGatewayProxy } from './createGatewayProxy';

export { createGatewayProxy };
17 changes: 17 additions & 0 deletions packages/rsocket-ws-gateway-client/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "es5",
"module": "es6",
"lib": ["dom", "es2015", "es2017.object", "es5", "es6", "es2016"],
"declaration": true,
"declarationDir": "./dist",
"outDir": "./dist",
"strict": true,
"moduleResolution": "node",
"baseUrl": "./src",
"esModuleInterop": true,
"noImplicitAny": false
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.*"]
}