Skip to content

Commit

Permalink
feat: add integration for service-oriented backends
Browse files Browse the repository at this point in the history
  • Loading branch information
raymondfeng committed May 3, 2018
1 parent 95acd11 commit 95b4025
Show file tree
Hide file tree
Showing 17 changed files with 583 additions and 6 deletions.
121 changes: 115 additions & 6 deletions docs/site/Calling-other-APIs-and-Web-Services.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,121 @@ summary:
---

Your API implementation often needs to interact with REST APIs, SOAP Web
Services or other forms of APIs.
Services, gRPC microservices, or other forms of APIs.

How to:
To facilitate calling other APIs or web services, we introduce `@loopback/service-proxy`
module to provide a common set of interfaces for interacting with backend services.

- Set up a Service
- Use services with controllers
- Reuse models between services and controllers
## Installation

{% include content/tbd.html %}
```
$ npm install --save @loopback/service-proxy
```

## Usage

### Define a data source for the service backend

```ts
import {DataSourceConstructor, juggler} from '@loopback/service-proxy';

const ds: juggler.DataSource = new DataSourceConstructor({
name: 'GoogleMapGeoCode',
connector: 'rest',
options: {
headers: {
'accept': 'application/json',
'content-type': 'application/json'
}
},
operations: [
{
template: {
method: 'GET',
url: 'http://maps.googleapis.com/maps/api/geocode/{format=json}',
query: {
address: '{street},{city},{zipcode}',
sensor: '{sensor=false}'
},
responsePath: '$.results[0].geometry.location[0]'
},
functions: {
geocode: ['street', 'city', 'zipcode']
}
}
]
});
```

### Bind data sources to the context

```ts
import {Context} from '@loopback/context';

const context = new Context();
context.bind('dataSources.geoService').to(ds);
```

**NOTE**: Once we start to support declarative datasources with `@loopback/boot`,
the datasource configuration files can be dropped into `src/datasources` to be
discovered and bound automatically.

### Declare the service interface

To promote type safety, we recommend you to declare data types and service
interfaces in TypeScript and use them to access the service proxy.

```ts
interface GeoCode {
lat: number;
lng: number;
}

interface GeoService {
geocode(street: string, city: string, zipcode: string): Promise<GeoCode>;
}
```

Alternately, we also provide a weakly-typed generic service interface as follows:

```ts
/**
* A generic service interface with any number of methods that return a promise
*/
export interface GenericService {
[methodName: string]: (...args: any[]) => Promise<any>;
}
```

To reference the `GenericService`:

```ts
import {GenericService} from '@loopback/service-proxy';
```

**NOTE**: We'll introduce tools in the future to generate TypeScript service
interfaces from service specifications such as OpenAPI spec.

### Declare service proxies for your controller

If your controller needs to interact with backend services, declare such
dependencies using `@serviceProxy` on constructor parameters or instance
properties of the controller class.

```ts
import {serviceProxy} from '@loopback/service-proxy';

export class MyController {

@serviceProxy('geoService')
private geoService: GeoService;

}
```

### Get an instance of your controller

```ts
context.bind('controllers.MyController').toClass(MyController);
const myController = await context.get<MyController>('controllers.MyController');
```
1 change: 1 addition & 0 deletions packages/service-proxy/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
25 changes: 25 additions & 0 deletions packages/service-proxy/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Copyright (c) IBM Corp. 2018. All Rights Reserved.
Node module: @loopback/service-proxy
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.
31 changes: 31 additions & 0 deletions packages/service-proxy/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# @loopback/service-proxy

This module provides a common set of interfaces for interacting with service
oriented backends such as REST APIs, SOAP Web Services, and gRPC microservices.

## Installation

```
$ npm install @loopback/service-proxy
```

## Basic use

See https://loopback.io/doc/en/lb4/Calling-other-APIs-and-web-services.html

## Contributions

- [Guidelines](https://github.com/strongloop/loopback-next/wiki/Contributing##guidelines)
- [Join the team](https://github.com/strongloop/loopback-next/issues/110)

## Tests

run 'npm test' from the root folder.

## Contributors

See [all contributors](https://github.com/strongloop/loopback-next/graphs/contributors).

## License

MIT
9 changes: 9 additions & 0 deletions packages/service-proxy/docs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"content": [
"./index.ts",
"./src/index.ts",
"./src/decorators/service.decorator.ts",
"./src/legacy-juggler-bridge.ts"
],
"codeSectionDepth": 4
}
6 changes: 6 additions & 0 deletions packages/service-proxy/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2017. All Rights Reserved.
// Node module: @loopback/service-proxy
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

export * from './dist';
6 changes: 6 additions & 0 deletions packages/service-proxy/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright IBM Corp. 2017. All Rights Reserved.
// Node module: @loopback/service-proxy
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

module.exports = require('./dist');
8 changes: 8 additions & 0 deletions packages/service-proxy/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/service-proxy
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

// DO NOT EDIT THIS FILE
// Add any additional (re)exports to src/index.ts instead.
export * from './src';
44 changes: 44 additions & 0 deletions packages/service-proxy/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"name": "@loopback/service-proxy-proxy",
"version": "0.2.0",
"description": "Service integration for LoopBack 4",
"engines": {
"node": ">=8"
},
"main": "index",
"scripts": {
"acceptance": "lb-mocha \"DIST/test/acceptance/**/*.js\"",
"build": "lb-tsc es2017",
"build:apidocs": "lb-apidocs",
"clean": "lb-clean loopback-service-proxy*.tgz dist package api-docs",
"integration": "lb-mocha \"DIST/test/integration/**/*.js\"",
"pretest": "npm run build",
"test": "lb-mocha \"DIST/test/unit/**/*.js\" \"DIST/test/acceptance/**/*.js\" \"DIST/test/integration/**/*.js\"",
"unit": "lb-mocha \"DIST/test/unit/**/*.js\"",
"verify": "npm pack && tar xf loopback-service-proxy*.tgz && tree package && npm run clean"
},
"author": "IBM",
"copyright.owner": "IBM Corp.",
"license": "MIT",
"devDependencies": {
"@loopback/build": "^0.2.0",
"@loopback/testlab": "^0.2.0"
},
"dependencies": {
"@loopback/context": "^0.8.1",
"@loopback/core": "^0.6.1",
"loopback-datasource-juggler": "^3.15.2"
},
"files": [
"README.md",
"index.js",
"index.d.ts",
"dist/src",
"api-docs",
"src"
],
"repository": {
"type": "git",
"url": "https://github.com/strongloop/loopback-next.git"
}
}
76 changes: 76 additions & 0 deletions packages/service-proxy/src/decorators/service.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/service-proxy
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {
MetadataAccessor,
inject,
Context,
Injection,
InjectionMetadata,
} from '@loopback/context';
import {getService, juggler} from '..';

/**
* Type definition for decorators returned by `@serviceProxy` decorator factory
*/
export type ServiceProxyDecorator = PropertyDecorator | ParameterDecorator;

export const SERVICE_PROXY_KEY = MetadataAccessor.create<
string,
ServiceProxyDecorator
>('service.proxy');

/**
* Metadata for a service proxy
*/
export class ServiceProxyMetadata implements InjectionMetadata {
decorator = '@serviceProxy';
dataSourceName?: string;
dataSource?: juggler.DataSource;

constructor(dataSource: string | juggler.DataSource) {
if (typeof dataSource === 'string') {
this.dataSourceName = dataSource;
} else {
this.dataSource = dataSource;
}
}
}

export function serviceProxy(dataSource: string | juggler.DataSource) {
return function(
target: Object,
key: symbol | string,
parameterIndex?: number,
) {
if (key || typeof parameterIndex === 'number') {
const meta = new ServiceProxyMetadata(dataSource);
inject('', meta, resolve)(target, key, parameterIndex);
} else {
throw new Error(
'@serviceProxy can only be applied to properties or method parameters',
);
}
};
}

/**
* Resolve the @repository injection
* @param ctx Context
* @param injection Injection metadata
*/
async function resolve(ctx: Context, injection: Injection) {
const meta = injection.metadata as ServiceProxyMetadata;
if (meta.dataSource) return getService(meta.dataSource);
if (meta.dataSourceName) {
const ds = await ctx.get<juggler.DataSource>(
'datasources.' + meta.dataSourceName,
);
return getService(ds);
}
throw new Error(
'@serviceProxy must provide a name or an instance of DataSource',
);
}
8 changes: 8 additions & 0 deletions packages/service-proxy/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/service-proxy
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

export * from './legacy-juggler-bridge';
export * from './loopback-datasource-juggler';
export * from './decorators/service.decorator';
29 changes: 29 additions & 0 deletions packages/service-proxy/src/legacy-juggler-bridge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright IBM Corp. 2017,2018. All Rights Reserved.
// Node module: @loopback/service-proxy
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

const jugglerModule = require('loopback-datasource-juggler');

import {juggler} from './loopback-datasource-juggler';

export const DataSourceConstructor = jugglerModule.DataSource as typeof juggler.DataSource;

/**
* A generic service interface with any number of methods that return a promise
*/
export interface GenericService {
// tslint:disable-next-line:no-any
[methodName: string]: (...args: any[]) => Promise<any>;
}

/**
* Get a service proxy from a LoopBack 3.x data source backed by
* service-oriented connectors such as `rest`, `soap`, and `grpc`.
*
* @param ds A legacy data source
* @typeparam T The generic type of service interface
*/
export function getService<T = GenericService>(ds: juggler.DataSource): T {
return ds.DataAccessObject as T;
}
Loading

0 comments on commit 95b4025

Please sign in to comment.