# http-client

HTTP client for Allied REST api.

Public / Private Key Required.

## Usage

### Basic
```ts
import client from '@alliedpayment/http-client';
```

```js
const client = require("@alliedpayment/http-client");

const main = async () => {
  try {
    const res = await client.get("url/to/resource");
    console.log(`response status code ${res.status}`);
    return res.data; // response body
  } catch (error) {
    console.log("failed to get resource", error);
  }
};

main();
```

### Proxy

```js
const client = require("@alliedpayment/http-client");
client.options.proxy =  {
    host: 'localhost',
    port: 8888,
    protocol: 'http',
  },
const main = async () => {
  try {
    const res = await client.get("url/to/resource");
    console.log(`response status code ${res.status}`);
    return res.data; // response body
  } catch (error) {
    console.log("failed to get resource", error);
  }
};

main();
```

### Request Options

```js
// underlying client is axios and config object is publicly available to support all axios supported request configs
// https://axios-http.com/docs/req_config

// example
const options = {
  timeout: 1000 * 30, // 30 second/s request timeout
  headers: { cookie: "smoke=true" },
};
const res = await client.get("url/to/resource", options);
```

### Request Delegates

You can pass a delegate function to wrap around the http request.

```js
const wrapper = async (promise) => {
  return await promise; // do nothing delegate
};
const res = await client.get("url/to/resource", options, wrapper);
```

#### Custom Response Parser

```js
const customParser = async (promise) => {
  try {
    const result = await promise;
    return `parse result for one: ${result.data.one}`;
  } catch (err) {
    log.error(err);
    return err.message;
  }
};

const res = await client.get("url/to/resource", options, customParser);
```

#### Custom Logging

```js
const customLogger = async (promise) => {
  console.log("i get logged before the request");
  const result = await promise;
  console.log("i get logged after the request", result);
  return result;
};

const res = await client.get("url/to/resource", options, customLogger);
```

#### Custom Error Handling

```js
const customErrorHandling = async (promise) => {
  try {
    console.log("i can try and catch exceptions and handle errors as needed");
    return await promise;
  } catch (err) {
    log.error(err);
    return null;
  }
};

const res = await client.get("url/to/resource", options, customErrorHandling);
```
