npm package: @opuscapita/service-client
Description: Module for http based inter-service-communication for OpusCapitaBusinessNetwork.
Latest version: 2.0.0

# @opucapita/service-client

**WARNING:** Starting with **version 1.0**, calls to the methods .get(), .post(), .put(), .patch() and .delete() will resolve and reject the returned promises in a different way that is **not compatible** to prior versions anymore. In order to be able to  rate a server response in an enhanced way, **resolved** promises get an array passed as input value containing two indexes. The first array **index (0)** inside represents the **result body** sent by the remote server. The second **index (1)** represents a light-weight **response object** containing status code and headers sent. **Rejected** promises are getting an **Error object** as usual containing the original (unparsed) **result body** inside their **message property**. And additional property called **response** provides status code and header sent.

---

This module provides a simple client class for inter-service communication for OpusCapita Business Network.
It is used for easily accessing remote HTTP services and is designed to use Consul in order to
dynamically get endpoint configurations to access the target service requested.

To have a look at the full API, please visit the related [wiki page](https://github.com/OpusCapitaBusinessNetwork/service-client/wiki).


### Minimum setup
First got to your local code directory and run:
```
npm install @opucapita/service-client
```
To go with the minimum setup, you need to have access to a running Consul server to get your endpoint configuration. Additionally you need a running web server to use the ServiceClient class.

If all this is set up, go to you code and add the following command:

```JS
const ServiceClient = require('@opucapita/service-client');

var client = new ServiceClient({ consul : { host : '{{your-consul-host}}' } });

// main => name of service endpoint in Consul.
// / => path to access on the web server.
client.get('main', '/').spread((result, response) => console.log(result, response));

// example: response contains an error.
client.get('main', '/invalid').catch(e => console.log(e.message, e.response.statusCode));
```

---

### Result and Response objects

#### On resolve
When a returned request promise is **resolved**, two objects are passed as the result. The **first** contains the **actual object returned** from the server, the **second** contains information about the **response context**. This object is defined like this:

```JS
responseObject = {
    statusCode : response.statusCode, // HTTP status code.
    headers : response.headers, // Array of HTTP headers.
    timeTaken : hrTimerResult // Duration of the service call in milliseconds .
}
```

Up to **version 1.6.5** responseObject used to contain additional field
```
    result : resultData, // Instance of the actual result object.
```
that repeated already the content of the first returned object

#### On reject
If a returned request promise gets **rejected**, an Error object is passed to the catch methods available. The passed object **gets extended by a response key** containing a response object defined like this:

```JS
response = {
    statusCode : response.statusCode, // HTTP status code.
    headers : response.headers, // Array of HTTP headers.
    result : resultData, // Instance of the actual result object.
    timeTaken : hrTimerResult // Duration of the service call in milliseconds .
}
```

#### Time taken
The duration of a service call available in the **responseObject** is measured using the process.hrtime() function and represents the full time in milliseconds a request took including all its preparations and processing.

---

### Origin service based authentication
ServiceClient allows using a service based **authentication** for service to service calls so an origin service can log-in using its **own security credentials**. To do calls using service credentials, you have to pass the **forceServiceToken** parameter to either of the request methods.

For configuration details see the **originService** key under [DefaultConfig](#default-configuration).

In order to use the consul configuration here, you have to provide the following keys set up in consul:

* {{your-service-name}}/service-client/client-username
* {{your-service-name}}/service-client/client-password
* {{your-service-name}}/service-client/scope
* {{your-service-name}}/service-client/client-key
* {{your-service-name}}/service-client/client-secret

The following keys are optional:

* {{your-service-name}}/originService/authService/name

---

### Default configuration

The default configuration object provides hints about what the module's standard behavior is like.

```JS
{
    mode : process.env.NODE_ENV === 'development' ? ServiceClient.Mode.Dev : ServiceClient.Mode.Productive,
    serializer : JSON.stringify,
    parser : JSON.parse,
    parserContentType : 'application/json',
    serializerContentType : 'application/json',
    alwaysResolveResponses : false,
    timeout : 60000,
    logger : null,
    consul : {
        host : 'consul'
    }
    additionalHeaders : {
        'Content-Type' : 'application/json',
        'X-Service-Type' : 'ocbesbn'
    },
    context : {
        headers : { }
    },
    caching : {
        driver : 'memory',
        defaultExpire : 600
    },
    originService: {
        getConfigFromConsul : true,
        authService : {
            name : 'auth'
        },
        username : null,
        password : null,
        scope : null,
        clientKey : null,
        clientSecret : null,
        scope : 'id, roles',
        tokenKey : 'X-USER-ID-TOKEN'
    }
}
```