npm package: @financeable/aggregation
Description: <!-- Start Summary [summary] --> ## Summary
Author: Financeable
Latest version: 0.16.0

# financeable-aggregation-api

<!-- Start Summary [summary] -->
## Summary


<!-- End Summary [summary] -->

<!-- Start Table of Contents [toc] -->
## Table of Contents
<!-- $toc-max-depth=2 -->
* [financeable-aggregation-api](#financeable-aggregation-api)
  * [SDK Installation](#sdk-installation)
  * [Requirements](#requirements)
  * [SDK Example Usage](#sdk-example-usage)
  * [Available Resources and Operations](#available-resources-and-operations)
  * [Standalone functions](#standalone-functions)
  * [Retries](#retries)
  * [Error Handling](#error-handling)
  * [Custom HTTP Client](#custom-http-client)
  * [Debugging](#debugging)

<!-- End Table of Contents [toc] -->

<!-- Start SDK Installation [installation] -->
## SDK Installation

The SDK can be installed with either [npm](https://www.npmjs.com/), [pnpm](https://pnpm.io/), [bun](https://bun.sh/) or [yarn](https://classic.yarnpkg.com/en/) package managers.

### NPM

```bash
npm add @financeable/aggregation
```

### PNPM

```bash
pnpm add @financeable/aggregation
```

### Bun

```bash
bun add @financeable/aggregation
```

### Yarn

```bash
yarn add @financeable/aggregation
```
<!-- End SDK Installation [installation] -->

<!-- Start Requirements [requirements] -->
## Requirements

For supported JavaScript runtimes, please consult [RUNTIMES.md](RUNTIMES.md).
<!-- End Requirements [requirements] -->

## SDK Example Usage

### Example

```typescript
const financeable = new Financeable({
  serverURL: "<URL of Financeable tenancy to send Application>",
});

async function run() {
  let result;

 const tokenRequest = await financeable.oauthToken.get({
      grantType: 'client_credentials',
      clientId: '<ClientId>',
      clientSecret: '<ClientSecret>',
      scope: 'application:read application:write',
    });

  try {
    result = await financeable.applications.create({
      data: {
        type: "commercial-secured-applications",
        attributes: {
          applicationType: "commercialSecured",
          associatedBrokerEmail: "someBrokerEmail@brokerage.com.au"
        },
        relationships: {
           loanDetails: {
              data: {
                type: 'loan-details',
                attributes: {
                  repayments: 12,
                  repaymentFrequency: 'monthly',
                  repaymentStructure: 'group-payments',
                  loanAmount: '10280.95',
                  purpose: 'Purchase of a motor vehicle',
                  term: 48,
                  balloon: 5,
                  deposit: '2500',
                  originationFee: 200,
                  rate: '0.15',
                  rateAdjustment: '-0.01',
                },
              }
           },
           asset: {
              data: {
                type: 'assets',
                attributes: {
                  assetType: ConsumerAssetType.MotorVehicle,
                  ageOfAsset: 3,
                  ageOfAssetAtEnd: 8,
                  condition: 'USED',
                  purpose: 'VEHICLE',
                  assetValue: '35000.00',
                  make: 'Toyota',
                  assetModel: 'Camry',
                  registrationNumber: 'ABC123',
                  registrationState: 'VIC',
                  vin: '1HGCM82633A123456',
                  supplierName: 'Mr and Mrs Smith',
                  supplierABN: '12345678901',
                  supplierAddress: '123 Car Street, Melbourne VIC 3000',
                  supplierPhone: '0412345678',
                  supplierContactName: 'John Smith',
                  supplierEmail: 'john.smith@mrandmrssmith.com.au',
                  privateSale: false,
                  typeOfSale: 'DEALER',
                  description: '2020 Toyota Camry Hybrid SL, Silver, 45,000km',
                  netAssetValue: '32000.00',
                  isLuxury: false,
                  additionalFees: '995.00',
                  additionalTaxes: '0.00',
                },
              },
            },
          customers: {
            data: [
              {
                type: "customers",
                attributes: {
                  title: "Ms",
                  firstName: "Bria",
                  lastName: "Schinner",
                  dateOfBirth: "2004-04-11",
                  idExpiryDate: "<value>",
                },
                relationships: {
                  addresses: {
                    data: [],
                  },
                },
              },
              {
                type: "customers",
                attributes: {
                  title: "Mr",
                  firstName: "Astrid",
                  lastName: "Schumm",
                  dateOfBirth: "1981-04-17",
                  idExpiryDate: "<value>",
                },
                relationships: {
                  addresses: {
                    data: [
                      {
                        type: "addresses",
                        attributes: {
                          addressType: "residential",
                          fullAddress: "42 Wallaby Way, Sydney NSW 2000",
                          city: "Sydney",
                          postCode: "2000",
                          streetAddress: "42 Wallaby Way",
                          addressLine2: "",
                          streetNumber: "42",
                          streetType: "Way",
                          street: "Wallaby",
                          state: "NSW",
                          country: "Australia",
                          status: "current",
                          monthsAt: 24,
                          yearsAt: 2,
                        },
                      },
                      {
                        type: "addresses",
                        attributes: {
                          addressType: "residential",
                          fullAddress: "42 Wallaby Way, Sydney NSW 2000",
                          city: "Sydney",
                          postCode: "2000",
                          streetAddress: "42 Wallaby Way",
                          addressLine2: "",
                          streetNumber: "42",
                          streetType: "Way",
                          street: "Wallaby",
                          state: "NSW",
                          country: "Australia",
                          status: "current",
                          monthsAt: 24,
                          yearsAt: 2,
                        },
                      },
                      {
                        type: "addresses",
                        attributes: {
                          addressType: "residential",
                          fullAddress: "42 Wallaby Way, Sydney NSW 2000",
                          city: "Sydney",
                          postCode: "2000",
                          streetAddress: "42 Wallaby Way",
                          addressLine2: "",
                          streetNumber: "42",
                          streetType: "Way",
                          street: "Wallaby",
                          state: "NSW",
                          country: "Australia",
                          status: "current",
                          monthsAt: 24,
                          yearsAt: 2,
                        },
                      },
                    ],
                  },
                },
              },
            ],
          },
          entities: {
            data: [
              {
                type: "entities",
                attributes: {
                  entityName: "Financeable Pty Ltd",
                  abn: "12345678901",
                  turnover: 1000000,
                  industryType: "Finance",
                  emails: [
                    "test@financeable.com.au",
                  ],
                  phoneNumbers: [
                    "0412345678",
                  ],
                },
              },
              {
                type: "entities",
                attributes: {
                  entityName: "Financeable Pty Ltd",
                  abn: "12345678901",
                  turnover: 1000000,
                  industryType: "Finance",
                  emails: [
                    "test@financeable.com.au",
                  ],
                  phoneNumbers: [
                    "0412345678",
                  ],
                },
              },
              {
                type: "entities",
                attributes: {
                  entityName: "Financeable Pty Ltd",
                  abn: "12345678901",
                  turnover: 1000000,
                  industryType: "Finance",
                  emails: [
                    "test@financeable.com.au",
                  ],
                  phoneNumbers: [
                    "0412345678",
                  ],
                },
              },
            ],
          },
        },
      },
    }, {
        fetchOptions: {
          headers: {
            authorization: `Bearer ${tokenRequest.accessToken}`,
          },
        },
      });

    // Handle the result
    console.log(result);
  } catch (err) {
    switch (true) {
      // The server response does not match the expected SDK schema
      case (err instanceof SDKValidationError): {
        // Pretty-print will provide a human-readable multi-line error message
        console.error(err.pretty());
        // Raw value may also be inspected
        console.error(err.rawValue);
        return;
      }
      case (err instanceof CreateApplicationResponseBody): {
        // Handle err.data$: CreateApplicationResponseBodyData
        console.error(err);
        return;
      }
      default: {
        // Other errors such as network errors, see HTTPClientErrors for more details
        throw err;
      }
    }
  }
}

run();

```
<!-- No SDK Example Usage [usage] -->

<!-- No Authentication [security] -->

<!-- Start Available Resources and Operations [operations] -->
## Available Resources and Operations

<details open>
<summary>Available methods</summary>

### [Applications](docs/sdks/applications/README.md)

* [create](docs/sdks/applications/README.md#create) - Create an application in the Financeable platform.
* [list](docs/sdks/applications/README.md#list) - List all applications from the tenant. This endpoint does not support the 'include' query parameter; relationships must be fetched via the 'Get Application' endpoint.
* [get](docs/sdks/applications/README.md#get) - Retrieve a specific application from the Financeable platform.

### [OauthToken](docs/sdks/oauthtoken/README.md)

* [get](docs/sdks/oauthtoken/README.md#get) - Obtain an OAuth client_credentials token

### [SupportingDocuments](docs/sdks/supportingdocuments/README.md)

* [create](docs/sdks/supportingdocuments/README.md#create) - Create a supporting document record in Financeable, and returns a pre-signed URL to upload this document with.

</details>
<!-- End Available Resources and Operations [operations] -->

<!-- Start Standalone functions [standalone-funcs] -->
## Standalone functions

All the methods listed above are available as standalone functions. These
functions are ideal for use in applications running in the browser, serverless
runtimes or other environments where application bundle size is a primary
concern. When using a bundler to build your application, all unused
functionality will be either excluded from the final bundle or tree-shaken away.

To read more about standalone functions, check [FUNCTIONS.md](./FUNCTIONS.md).

<details>

<summary>Available standalone functions</summary>

- [`applicationsCreate`](docs/sdks/applications/README.md#create) - Create an application in the Financeable platform.
- [`applicationsGet`](docs/sdks/applications/README.md#get) - Retrieve a specific application from the Financeable platform.
- [`applicationsList`](docs/sdks/applications/README.md#list) - List all applications from the tenant. This endpoint does not support the 'include' query parameter; relationships must be fetched via the 'Get Application' endpoint.
- [`oauthTokenGet`](docs/sdks/oauthtoken/README.md#get) - Obtain an OAuth client_credentials token
- [`supportingDocumentsCreate`](docs/sdks/supportingdocuments/README.md#create) - Create a supporting document record in Financeable, and returns a pre-signed URL to upload this document with.

</details>
<!-- End Standalone functions [standalone-funcs] -->

<!-- Start Retries [retries] -->
## Retries

Some of the endpoints in this SDK support retries.  If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API.  However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
```typescript
import { Financeable } from "@financeable/aggregation";

const financeable = new Financeable({
  clientCredentials: process.env["FINANCEABLE_CLIENT_CREDENTIALS"] ?? "",
});

async function run() {
  const result = await financeable.applications.create({
    data: {
      type: "entities",
      attributes: {
        applicationType: "consumerSecured",
        associatedBrokerEmail: "<value>",
      },
      relationships: {
        customers: {
          data: [
            {
              type: "customers",
              attributes: {
                title: "Mr",
                firstName: "Courtney",
                lastName: "Greenfelder",
                dateOfBirth: "1981-06-22",
                idExpiryDate: "<value>",
              },
              relationships: {
                addresses: {
                  data: [
                    {
                      type: "addresses",
                      attributes: {
                        id: "12345678901",
                        addressType: "residential",
                        fullAddress: "42 Wallaby Way, Sydney NSW 2000",
                        city: "Sydney",
                        postCode: "2000",
                        streetAddress: "42 Wallaby Way",
                        addressLine2: "",
                        streetNumber: "42",
                        streetType: "Way",
                        street: "Wallaby",
                        state: "NSW",
                        country: "Australia",
                        status: "current",
                        monthsAt: 24,
                        yearsAt: 2,
                      },
                    },
                  ],
                },
              },
            },
            {
              type: "customers",
              attributes: {
                title: "Mr",
                firstName: "Courtney",
                lastName: "Greenfelder",
                dateOfBirth: "1981-06-22",
                idExpiryDate: "<value>",
              },
              relationships: {
                addresses: {
                  data: [
                    {
                      type: "addresses",
                      attributes: {
                        id: "12345678901",
                        addressType: "residential",
                        fullAddress: "42 Wallaby Way, Sydney NSW 2000",
                        city: "Sydney",
                        postCode: "2000",
                        streetAddress: "42 Wallaby Way",
                        addressLine2: "",
                        streetNumber: "42",
                        streetType: "Way",
                        street: "Wallaby",
                        state: "NSW",
                        country: "Australia",
                        status: "current",
                        monthsAt: 24,
                        yearsAt: 2,
                      },
                    },
                  ],
                },
              },
            },
            {
              type: "customers",
              attributes: {
                title: "Mr",
                firstName: "Courtney",
                lastName: "Greenfelder",
                dateOfBirth: "1981-06-22",
                idExpiryDate: "<value>",
              },
              relationships: {
                addresses: {
                  data: [
                    {
                      type: "addresses",
                      attributes: {
                        id: "12345678901",
                        addressType: "residential",
                        fullAddress: "42 Wallaby Way, Sydney NSW 2000",
                        city: "Sydney",
                        postCode: "2000",
                        streetAddress: "42 Wallaby Way",
                        addressLine2: "",
                        streetNumber: "42",
                        streetType: "Way",
                        street: "Wallaby",
                        state: "NSW",
                        country: "Australia",
                        status: "current",
                        monthsAt: 24,
                        yearsAt: 2,
                      },
                    },
                  ],
                },
              },
            },
          ],
        },
        asset: {
          data: {
            type: "assets",
            attributes: {
              id: "12345678901",
              ageOfAsset: 3,
              ageOfAssetAtEnd: 8,
              condition: "USED",
              assetType: "CARAVAN",
              assetValue: "35000.00",
              make: "Toyota",
              assetModel: "Camry",
              registrationNumber: "ABC123",
              registrationState: "VIC",
              vin: "1HGCM82633A123456",
              supplierName: "Mr and Mrs Smith",
              supplierABN: "12345678901",
              supplierAddress: "123 Car Street, Melbourne VIC 3000",
              supplierPhone: "0412345678",
              supplierContactName: "John Smith",
              supplierEmail: "john.smith@mrandmrssmith.com.au",
              privateSale: false,
              typeOfSale: "AUTHORISED_SELLER",
              description: "2020 Toyota Camry Hybrid SL, Silver, 45,000km",
              netAssetValue: "32000.00",
              isLuxury: false,
              additionalFees: "995.00",
              additionalTaxes: "0.00",
            },
          },
        },
      },
    },
  }, {
    retries: {
      strategy: "backoff",
      backoff: {
        initialInterval: 1,
        maxInterval: 50,
        exponent: 1.1,
        maxElapsedTime: 100,
      },
      retryConnectionErrors: false,
    },
  });

  console.log(result);
}

run();

```

If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
```typescript
import { Financeable } from "@financeable/aggregation";

const financeable = new Financeable({
  retryConfig: {
    strategy: "backoff",
    backoff: {
      initialInterval: 1,
      maxInterval: 50,
      exponent: 1.1,
      maxElapsedTime: 100,
    },
    retryConnectionErrors: false,
  },
  clientCredentials: process.env["FINANCEABLE_CLIENT_CREDENTIALS"] ?? "",
});

async function run() {
  const result = await financeable.applications.create({
    data: {
      type: "entities",
      attributes: {
        applicationType: "consumerSecured",
        associatedBrokerEmail: "<value>",
      },
      relationships: {
        customers: {
          data: [
            {
              type: "customers",
              attributes: {
                title: "Mr",
                firstName: "Courtney",
                lastName: "Greenfelder",
                dateOfBirth: "1981-06-22",
                idExpiryDate: "<value>",
              },
              relationships: {
                addresses: {
                  data: [
                    {
                      type: "addresses",
                      attributes: {
                        id: "12345678901",
                        addressType: "residential",
                        fullAddress: "42 Wallaby Way, Sydney NSW 2000",
                        city: "Sydney",
                        postCode: "2000",
                        streetAddress: "42 Wallaby Way",
                        addressLine2: "",
                        streetNumber: "42",
                        streetType: "Way",
                        street: "Wallaby",
                        state: "NSW",
                        country: "Australia",
                        status: "current",
                        monthsAt: 24,
                        yearsAt: 2,
                      },
                    },
                  ],
                },
              },
            },
            {
              type: "customers",
              attributes: {
                title: "Mr",
                firstName: "Courtney",
                lastName: "Greenfelder",
                dateOfBirth: "1981-06-22",
                idExpiryDate: "<value>",
              },
              relationships: {
                addresses: {
                  data: [
                    {
                      type: "addresses",
                      attributes: {
                        id: "12345678901",
                        addressType: "residential",
                        fullAddress: "42 Wallaby Way, Sydney NSW 2000",
                        city: "Sydney",
                        postCode: "2000",
                        streetAddress: "42 Wallaby Way",
                        addressLine2: "",
                        streetNumber: "42",
                        streetType: "Way",
                        street: "Wallaby",
                        state: "NSW",
                        country: "Australia",
                        status: "current",
                        monthsAt: 24,
                        yearsAt: 2,
                      },
                    },
                  ],
                },
              },
            },
            {
              type: "customers",
              attributes: {
                title: "Mr",
                firstName: "Courtney",
                lastName: "Greenfelder",
                dateOfBirth: "1981-06-22",
                idExpiryDate: "<value>",
              },
              relationships: {
                addresses: {
                  data: [
                    {
                      type: "addresses",
                      attributes: {
                        id: "12345678901",
                        addressType: "residential",
                        fullAddress: "42 Wallaby Way, Sydney NSW 2000",
                        city: "Sydney",
                        postCode: "2000",
                        streetAddress: "42 Wallaby Way",
                        addressLine2: "",
                        streetNumber: "42",
                        streetType: "Way",
                        street: "Wallaby",
                        state: "NSW",
                        country: "Australia",
                        status: "current",
                        monthsAt: 24,
                        yearsAt: 2,
                      },
                    },
                  ],
                },
              },
            },
          ],
        },
        asset: {
          data: {
            type: "assets",
            attributes: {
              id: "12345678901",
              ageOfAsset: 3,
              ageOfAssetAtEnd: 8,
              condition: "USED",
              assetType: "CARAVAN",
              assetValue: "35000.00",
              make: "Toyota",
              assetModel: "Camry",
              registrationNumber: "ABC123",
              registrationState: "VIC",
              vin: "1HGCM82633A123456",
              supplierName: "Mr and Mrs Smith",
              supplierABN: "12345678901",
              supplierAddress: "123 Car Street, Melbourne VIC 3000",
              supplierPhone: "0412345678",
              supplierContactName: "John Smith",
              supplierEmail: "john.smith@mrandmrssmith.com.au",
              privateSale: false,
              typeOfSale: "AUTHORISED_SELLER",
              description: "2020 Toyota Camry Hybrid SL, Silver, 45,000km",
              netAssetValue: "32000.00",
              isLuxury: false,
              additionalFees: "995.00",
              additionalTaxes: "0.00",
            },
          },
        },
      },
    },
  });

  console.log(result);
}

run();

```
<!-- End Retries [retries] -->

<!-- Start Error Handling [errors] -->
## Error Handling

[`FinanceableError`](./src/models/errors/financeableerror.ts) is the base class for all HTTP error responses. It has the following properties:

| Property            | Type       | Description                                            |
| ------------------- | ---------- | ------------------------------------------------------ |
| `error.message`     | `string`   | Error message                                          |
| `error.statusCode`  | `number`   | HTTP response status code eg `404`                     |
| `error.headers`     | `Headers`  | HTTP response headers                                  |
| `error.body`        | `string`   | HTTP body. Can be empty string if no body is returned. |
| `error.rawResponse` | `Response` | Raw HTTP response                                      |

### Example
```typescript
import { Financeable } from "@financeable/aggregation";
import * as errors from "@financeable/aggregation/models/errors";

const financeable = new Financeable({
  clientCredentials: process.env["FINANCEABLE_CLIENT_CREDENTIALS"] ?? "",
});

async function run() {
  try {
    const result = await financeable.applications.create({
      data: {
        type: "entities",
        attributes: {
          applicationType: "consumerSecured",
          associatedBrokerEmail: "<value>",
        },
        relationships: {
          customers: {
            data: [
              {
                type: "customers",
                attributes: {
                  title: "Mr",
                  firstName: "Courtney",
                  lastName: "Greenfelder",
                  dateOfBirth: "1981-06-22",
                  idExpiryDate: "<value>",
                },
                relationships: {
                  addresses: {
                    data: [
                      {
                        type: "addresses",
                        attributes: {
                          id: "12345678901",
                          addressType: "residential",
                          fullAddress: "42 Wallaby Way, Sydney NSW 2000",
                          city: "Sydney",
                          postCode: "2000",
                          streetAddress: "42 Wallaby Way",
                          addressLine2: "",
                          streetNumber: "42",
                          streetType: "Way",
                          street: "Wallaby",
                          state: "NSW",
                          country: "Australia",
                          status: "current",
                          monthsAt: 24,
                          yearsAt: 2,
                        },
                      },
                    ],
                  },
                },
              },
              {
                type: "customers",
                attributes: {
                  title: "Mr",
                  firstName: "Courtney",
                  lastName: "Greenfelder",
                  dateOfBirth: "1981-06-22",
                  idExpiryDate: "<value>",
                },
                relationships: {
                  addresses: {
                    data: [
                      {
                        type: "addresses",
                        attributes: {
                          id: "12345678901",
                          addressType: "residential",
                          fullAddress: "42 Wallaby Way, Sydney NSW 2000",
                          city: "Sydney",
                          postCode: "2000",
                          streetAddress: "42 Wallaby Way",
                          addressLine2: "",
                          streetNumber: "42",
                          streetType: "Way",
                          street: "Wallaby",
                          state: "NSW",
                          country: "Australia",
                          status: "current",
                          monthsAt: 24,
                          yearsAt: 2,
                        },
                      },
                    ],
                  },
                },
              },
              {
                type: "customers",
                attributes: {
                  title: "Mr",
                  firstName: "Courtney",
                  lastName: "Greenfelder",
                  dateOfBirth: "1981-06-22",
                  idExpiryDate: "<value>",
                },
                relationships: {
                  addresses: {
                    data: [
                      {
                        type: "addresses",
                        attributes: {
                          id: "12345678901",
                          addressType: "residential",
                          fullAddress: "42 Wallaby Way, Sydney NSW 2000",
                          city: "Sydney",
                          postCode: "2000",
                          streetAddress: "42 Wallaby Way",
                          addressLine2: "",
                          streetNumber: "42",
                          streetType: "Way",
                          street: "Wallaby",
                          state: "NSW",
                          country: "Australia",
                          status: "current",
                          monthsAt: 24,
                          yearsAt: 2,
                        },
                      },
                    ],
                  },
                },
              },
            ],
          },
          asset: {
            data: {
              type: "assets",
              attributes: {
                id: "12345678901",
                ageOfAsset: 3,
                ageOfAssetAtEnd: 8,
                condition: "USED",
                assetType: "CARAVAN",
                assetValue: "35000.00",
                make: "Toyota",
                assetModel: "Camry",
                registrationNumber: "ABC123",
                registrationState: "VIC",
                vin: "1HGCM82633A123456",
                supplierName: "Mr and Mrs Smith",
                supplierABN: "12345678901",
                supplierAddress: "123 Car Street, Melbourne VIC 3000",
                supplierPhone: "0412345678",
                supplierContactName: "John Smith",
                supplierEmail: "john.smith@mrandmrssmith.com.au",
                privateSale: false,
                typeOfSale: "AUTHORISED_SELLER",
                description: "2020 Toyota Camry Hybrid SL, Silver, 45,000km",
                netAssetValue: "32000.00",
                isLuxury: false,
                additionalFees: "995.00",
                additionalTaxes: "0.00",
              },
            },
          },
        },
      },
    });

    console.log(result);
  } catch (error) {
    if (error instanceof errors.FinanceableError) {
      console.log(error.message);
      console.log(error.statusCode);
      console.log(error.body);
      console.log(error.headers);
    }
  }
}

run();

```

### Error Classes
**Primary error:**
* [`FinanceableError`](./src/models/errors/financeableerror.ts): The base class for HTTP error responses.

<details><summary>Less common errors (6)</summary>

<br />

**Network errors:**
* [`ConnectionError`](./src/models/errors/httpclienterrors.ts): HTTP client was unable to make a request to a server.
* [`RequestTimeoutError`](./src/models/errors/httpclienterrors.ts): HTTP request timed out due to an AbortSignal signal.
* [`RequestAbortedError`](./src/models/errors/httpclienterrors.ts): HTTP request was aborted by the client.
* [`InvalidRequestError`](./src/models/errors/httpclienterrors.ts): Any input used to create a request is invalid.
* [`UnexpectedClientError`](./src/models/errors/httpclienterrors.ts): Unrecognised or unexpected error.


**Inherit from [`FinanceableError`](./src/models/errors/financeableerror.ts)**:
* [`ResponseValidationError`](./src/models/errors/responsevalidationerror.ts): Type mismatch between the data returned from the server and the structure expected by the SDK. See `error.rawValue` for the raw value and `error.pretty()` for a nicely formatted multi-line string.

</details>
<!-- End Error Handling [errors] -->

<!-- No Server Selection [server] -->

<!-- Start Custom HTTP Client [http-client] -->
## Custom HTTP Client

The TypeScript SDK makes API calls using an `HTTPClient` that wraps the native
[Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). This
client is a thin wrapper around `fetch` and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.

The `HTTPClient` constructor takes an optional `fetcher` argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.

The following example shows how to use the `"beforeRequest"` hook to to add a
custom header and a timeout to requests and how to use the `"requestError"` hook
to log errors:

```typescript
import { Financeable } from "@financeable/aggregation";
import { HTTPClient } from "@financeable/aggregation/lib/http";

const httpClient = new HTTPClient({
  // fetcher takes a function that has the same signature as native `fetch`.
  fetcher: (request) => {
    return fetch(request);
  }
});

httpClient.addHook("beforeRequest", (request) => {
  const nextRequest = new Request(request, {
    signal: request.signal || AbortSignal.timeout(5000)
  });

  nextRequest.headers.set("x-custom-header", "custom value");

  return nextRequest;
});

httpClient.addHook("requestError", (error, request) => {
  console.group("Request Error");
  console.log("Reason:", `${error}`);
  console.log("Endpoint:", `${request.method} ${request.url}`);
  console.groupEnd();
});

const sdk = new Financeable({ httpClient: httpClient });
```
<!-- End Custom HTTP Client [http-client] -->

<!-- Start Debugging [debug] -->
## Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass a logger that matches `console`'s interface as an SDK option.

> [!WARNING]
> Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.

```typescript
import { Financeable } from "@financeable/aggregation";

const sdk = new Financeable({ debugLogger: console });
```

You can also enable a default debug logger by setting an environment variable `FINANCEABLE_DEBUG` to true.
<!-- End Debugging [debug] -->

<!-- Placeholder for Future Speakeasy SDK Sections -->