🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
DemoInstallSign in
Socket

@financeable/aggregation

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@financeable/aggregation

## Summary

0.5.1
latest
Source
npm
Version published
Weekly downloads
92
130%
Maintainers
1
Weekly downloads
 
Created
Source

financeable-aggregation-api

Summary

Table of Contents

  • financeable-aggregation-api

SDK Installation

The SDK can be installed with either npm, pnpm, bun or yarn package managers.

NPM

npm add https://github.com/financeable-com-au/financeable-aggregation-api

PNPM

pnpm add https://github.com/financeable-com-au/financeable-aggregation-api

Bun

bun add https://github.com/financeable-com-au/financeable-aggregation-api

Yarn

yarn add https://github.com/financeable-com-au/financeable-aggregation-api zod

# Note that Yarn does not install peer dependencies automatically. You will need
# to install zod as shown above.

Requirements

For supported JavaScript runtimes, please consult RUNTIMES.md.

SDK Example Usage

import { Financeable } from "@financeable/aggregation";
import { ConsumerAssetType } from "@financeable/aggregation/models/components"

const financeable = new Financeable({
  serverURL: "<Server_URL>
});

async function run() {

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

    const result = await financeable.applications.create(
      {
        data: {
          type: 'applications',
          attributes: {
            purpose: 'Purchase of a motor vehicle',
            applicationType: 'consumer',
          },
          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',
                },
              },
            },
            customers: {
              data: [
                {
                  type: 'customers',
                  attributes: {
                    title: 'Mr',
                    firstName: 'John',
                    emailAddresses: ["john.smith@mrandmrssmith.com.au"],
                    phoneNumbers: ["0412345678"],
                    lastName: 'Smith',
                    dateOfBirth: '1990-01-28',
                    idExpiryDate: '2025-11-15',
                    idType: 'licence',
                    idNumber: '12345678',
                  },
                  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: 6,
                            yearsAt: 2,
                          },
                        },
                        {
                          type: 'addresses',
                          attributes: {
                            addressType: 'residential',
                            fullAddress: '28 Wallaby Way, Sydney NSW 2000',
                            city: 'Sydney',
                            postCode: '2000',
                            streetAddress: '28 Wallaby Way',
                            addressLine2: '',
                            streetNumber: '28',
                            streetType: 'Way',
                            street: 'Wallaby',
                            state: 'NSW',
                            country: 'Australia',
                            status: 'previous',
                            monthsAt: 0,
                            yearsAt: 2,
                          },
                        },
                      ],
                    },
                  },
                },
              ],
            },
            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',
                },
              },
            },
          },
        },
      },
      {
        fetchOptions: {
          headers: {
            authorization: `Bearer ${tokenRequest.accessToken}`,
          },
        },
      },
    );

  // Handle the result
  console.log(result);
}

run();

Available Resources and Operations

Available methods

applications

  • create - Create an application in the Financeable platform.

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.

Available standalone functions

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:

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

const financeable = new Financeable({
  serverURL: '<ServerUrl>'
})

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

    const result = await financeable.applications.create(
      {
        data: {
          type: 'applications',
          attributes: {
            purpose: 'Purchase of a motor vehicle',
            applicationType: 'consumer',
          },
          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',
                },
              },
            },
            customers: {
              data: [
                {
                  type: 'customers',
                  attributes: {
                    title: 'Mr',
                    firstName: 'John',
                    emailAddresses: ["john.smith@mrandmrssmith.com.au"],
                    phoneNumbers: ["0412345678"],
                    lastName: 'Smith',
                    dateOfBirth: '1990-01-28',
                    idExpiryDate: '2025-11-15',
                    idType: 'licence',
                    idNumber: '12345678',
                  },
                  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: 6,
                            yearsAt: 2,
                          },
                        },
                        {
                          type: 'addresses',
                          attributes: {
                            addressType: 'residential',
                            fullAddress: '28 Wallaby Way, Sydney NSW 2000',
                            city: 'Sydney',
                            postCode: '2000',
                            streetAddress: '28 Wallaby Way',
                            addressLine2: '',
                            streetNumber: '28',
                            streetType: 'Way',
                            street: 'Wallaby',
                            state: 'NSW',
                            country: 'Australia',
                            status: 'previous',
                            monthsAt: 0,
                            yearsAt: 2,
                          },
                        },
                      ],
                    },
                  },
                },
              ],
            },
            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',
                },
              },
            },
          },
        },
      },
      {
        fetchOptions: {
          headers: {
            authorization: `Bearer ${tokenRequest.accessToken}`,
          },
        },
        retries: {
          strategy: "backoff",
          backoff: {
            initialInterval: 1,
            maxInterval: 50,
            exponent: 1.1,
            maxElapsedTime: 100,
          },
          retryConnectionErrors: false,
        }
      },
    );

  // Handle the result
  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:

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

const financeable = new Financeable({
  serverURL: "<ServerURL>",
  retryConfig: {
    strategy: "backoff",
    backoff: {
      initialInterval: 1,
      maxInterval: 50,
      exponent: 1.1,
      maxElapsedTime: 100,
    },
    retryConnectionErrors: false,
  },
});

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

    const result = await financeable.applications.create(
      {
        data: {
          type: 'applications',
          attributes: {
            purpose: 'Purchase of a motor vehicle',
            applicationType: 'consumer',
          },
          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',
                },
              },
            },
            customers: {
              data: [
                {
                  type: 'customers',
                  attributes: {
                    title: 'Mr',
                    firstName: 'John',
                    emailAddresses: ["john.smith@mrandmrssmith.com.au"],
                    phoneNumbers: ["0412345678"],
                    lastName: 'Smith',
                    dateOfBirth: '1990-01-28',
                    idExpiryDate: '2025-11-15',
                    idType: 'licence',
                    idNumber: '12345678',
                  },
                  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: 6,
                            yearsAt: 2,
                          },
                        },
                        {
                          type: 'addresses',
                          attributes: {
                            addressType: 'residential',
                            fullAddress: '28 Wallaby Way, Sydney NSW 2000',
                            city: 'Sydney',
                            postCode: '2000',
                            streetAddress: '28 Wallaby Way',
                            addressLine2: '',
                            streetNumber: '28',
                            streetType: 'Way',
                            street: 'Wallaby',
                            state: 'NSW',
                            country: 'Australia',
                            status: 'previous',
                            monthsAt: 0,
                            yearsAt: 2,
                          },
                        },
                      ],
                    },
                  },
                },
              ],
            },
            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',
                },
              },
            },
          },
        },
      },
      {
        fetchOptions: {
          headers: {
            authorization: `Bearer ${tokenRequest.accessToken}`,
          },
        }
      },
    );

  // Handle the result
  console.log(result);
}

run();

Error Handling

Some methods specify known errors which can be thrown. All the known errors are enumerated in the models/errors/errors.ts module. The known errors for a method are documented under the Errors tables in SDK docs. For example, the create method may throw the following errors:

Error TypeStatus CodeContent Type
errors.CreateApplicationResponseBody403application/json
errors.APIError4XX, 5XX*/*

If the method throws an error and it is not captured by the known errors, it will default to throwing a APIError.

import { Financeable } from "@financeable/aggregation";
import {
  CreateApplicationResponseBody,
  SDKValidationError,
} from "@financeable/aggregation/models/errors";
import { ConsumerAssetType } from "@financeable/aggregation/models/components"

const financeable = new Financeable({
  serverURL: "<ServerURL>"
});

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

    result = await financeable.applications.create({
      data: {
        type: "applications",
        attributes: {
          purpose: "Purchase of a motor vehicle",
          applicationType: "consumer",
        },
        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",
              },
            },
          },
          customers: {
            data: [
              {
                type: "customers",
                attributes: {
                  title: "Mr",
                  firstName: "John",
                  lastName: "Smith",
                  dateOfBirth: "1982-06-21",
                  idExpiryDate: "2030-03-15",
                  idType: "licence",
                  idNumber: "12345678",
                },
                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: 5,
                          yearsAt: 2,
                        },
                      },
                      {
                        type: "addresses",
                        attributes: {
                          addressType: "residential",
                          fullAddress: "28 Wallaby Way, Sydney NSW 2000",
                          city: "Sydney",
                          postCode: "2000",
                          streetAddress: "28 Wallaby Way",
                          addressLine2: "",
                          streetNumber: "28",
                          streetType: "Way",
                          street: "Wallaby",
                          state: "NSW",
                          country: "Australia",
                          status: "previous",
                          monthsAt: 0,
                          yearsAt: 5,
                        },
                      },
                    ],
                  },
                },
              },
            ],
          },
          asset: {
            data: {
              type: "asset",
              attributes: {
                ageOfAsset: 3,
                ageOfAssetAtEnd: 8,
                condition: "USED",
                assetType: ConsumerAssetType.MotorVehicle,
                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",
              },
            },
          },
        },
      },
      {
        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();

Validation errors can also occur when either method arguments or data returned from the server do not match the expected format. The SDKValidationError that is thrown as a result will capture the raw value that failed validation in an attribute called rawValue. Additionally, a pretty() method is available on this error that can be used to log a nicely formatted multi-line string since validation errors can list many issues and the plain error string may be difficult read when debugging.

In some rare cases, the SDK can fail to get a response from the server or even make the request due to unexpected circumstances such as network conditions. These types of errors are captured in the models/errors/httpclienterrors.ts module:

HTTP Client ErrorDescription
RequestAbortedErrorHTTP request was aborted by the client
RequestTimeoutErrorHTTP request timed out due to an AbortSignal signal
ConnectionErrorHTTP client was unable to make a request to a server
InvalidRequestErrorAny input used to create a request is invalid
UnexpectedClientErrorUnrecognised or unexpected error

Server Selection

Override Server URL Per-Client

The default server can also be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:

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

const financeable = new Financeable({
  serverURL: "https://dev.server.api.financeable.com.au",
});

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

    const result = await financeable.applications.create({
      data: {
        type: "applications",
        attributes: {
          purpose: "Purchase of a motor vehicle",
          applicationType: "consumer",
        },
        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",
              },
            },
          },
          customers: {
            data: [
              {
                type: "customers",
                attributes: {
                  title: "Mr",
                  firstName: "John",
                  lastName: "Smith",
                  dateOfBirth: "1950-04-20",
                  idExpiryDate: "2029-06-13",
                  idType: "licence",
                  idNumber: "12345678",
                },
                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: 11,
                          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: "previous",
                          monthsAt: 2,
                          yearsAt: 2,
                        },
                      },
                    ],
                  },
                },
              },
            ],
          },
          asset: {
            data: {
              type: "assets",
              attributes: {
                ageOfAsset: 3,
                ageOfAssetAtEnd: 8,
                condition: "USED",
                assetType: ConsumerAssetType.MotorVehicle,
                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",
              },
            },
          },
        },
      }},
      {
        fetchOptions: {
          headers: {
            authorization: `Bearer ${tokenRequest.accessToken}`,
          },
        }
      },
   );

  // Handle the result
  console.log(result);
}

run();

Custom HTTP Client

The TypeScript SDK makes API calls using an HTTPClient that wraps the native 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:

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 });

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.

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.

Summary

Table of Contents

SDK Installation

The SDK can be installed with either npm, pnpm, bun or yarn package managers.

NPM

npm add @financeable/aggregation

PNPM

pnpm add @financeable/aggregation

Bun

bun add @financeable/aggregation

Yarn

yarn add @financeable/aggregation zod

# Note that Yarn does not install peer dependencies automatically. You will need
# to install zod as shown above.

Requirements

For supported JavaScript runtimes, please consult RUNTIMES.md.

SDK Example Usage

Example

import { Financeable } from "@financeable/aggregation";
import { ConsumerAssetType } from "@financeable/aggregation/models/components"

const financeable = new Financeable({
  serverURL: '<ServerURL>',
});

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

  const result = await financeable.applications.create({
    data: {
      type: "applications",
      attributes: {
        purpose: "Purchase of a motor vehicle",
        applicationType: "consumer",
      },
      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",
            },
          },
        },
        customers: {
          data: [
            {
              type: "customers",
              attributes: {
                title: "Mr",
                firstName: "John",
                lastName: "Smith",
                dateOfBirth: "1990-06-28",
                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: 6,
                        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: "previous",
                        monthsAt: 0,
                        yearsAt: 5,
                      },
                    },
                  ],
                },
              },
            },
          ],
        },
        asset: {
          data: {
            type: "assets",
            attributes: {
              ageOfAsset: 3,
              ageOfAssetAtEnd: 8,
              condition: "USED",
              assetType: ConsumerAssetType.MotorVehicle,
              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",
            },
          },
        },
      },
    },
    {
      fetchOptions: {
        headers: {
          authorization: `Bearer ${tokenRequest.accessToken}`,
        },
      },
    },
  });

  // Handle the result
  console.log(result);
}

run();

Available Resources and Operations

Available methods

applications

  • create - Create an application in the Financeable platform.
  • list - Retrieve a list of applications
  • get - Retrieve an application by its ID

oauthToken

  • get - Obtain an OAuth client_credentials token

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.

Available standalone functions

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:

import { Financeable } from "@financeable/aggregation";
import { CommercialAssetType } from "@financeable/aggregation/models/components";

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

async function run() {
  const result = await financeable.applications.create({
    data: {
      type: "applications",
      attributes: {
        purpose: "Purchase of a motor vehicle",
        applicationType: "consumer",
      },
      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",
            },
          },
        },
        entities: {
          data: [
            {
              type: "entities",
              attributes: {
                businessNames: [
                  "<value>",
                  "<value>",
                ],
                entityName: "<value>",
                abn: "<value>",
                acn: "<value>",
                state: "QLD",
                entityType: "Australian Private Company",
              },
            },
          ],
        },
        customers: {
          data: [
            {
              type: "customers",
              attributes: {
                title: "Mr",
                firstName: "John",
                lastName: "Smith",
                dateOfBirth: "01-01-1990",
                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,
                      },
                    },
                  ],
                },
              },
            },
          ],
        },
        asset: {
          data: {
            type: "assets",
            attributes: {
              ageOfAsset: 3,
              ageOfAssetAtEnd: 8,
              condition: "USED",
              assetType: CommercialAssetType.MotorVehicleLessThan45Tonnes,
              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",
            },
          },
        },
      },
    },
  }, {
    retries: {
      strategy: "backoff",
      backoff: {
        initialInterval: 1,
        maxInterval: 50,
        exponent: 1.1,
        maxElapsedTime: 100,
      },
      retryConnectionErrors: false,
    },
  });

  // Handle the result
  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:

import { Financeable } from "@financeable/aggregation";
import { CommercialAssetType } from "@financeable/aggregation/models/components";

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: "applications",
      attributes: {
        purpose: "Purchase of a motor vehicle",
        applicationType: "consumer",
      },
      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",
            },
          },
        },
        entities: {
          data: [
            {
              type: "entities",
              attributes: {
                businessNames: [
                  "<value>",
                  "<value>",
                ],
                entityName: "<value>",
                abn: "<value>",
                acn: "<value>",
                state: "QLD",
                entityType: "Australian Private Company",
              },
            },
          ],
        },
        customers: {
          data: [
            {
              type: "customers",
              attributes: {
                title: "Mr",
                firstName: "John",
                lastName: "Smith",
                dateOfBirth: "01-01-1990",
                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,
                      },
                    },
                  ],
                },
              },
            },
          ],
        },
        asset: {
          data: {
            type: "assets",
            attributes: {
              ageOfAsset: 3,
              ageOfAssetAtEnd: 8,
              condition: "USED",
              assetType: CommercialAssetType.MotorVehicleLessThan45Tonnes,
              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",
            },
          },
        },
      },
    },
  });

  // Handle the result
  console.log(result);
}

run();

Error Handling

Some methods specify known errors which can be thrown. All the known errors are enumerated in the models/errors/errors.ts module. The known errors for a method are documented under the Errors tables in SDK docs. For example, the create method may throw the following errors:

Error TypeStatus CodeContent Type
errors.ResponseBody403application/json
errors.APIError4XX, 5XX*/*

If the method throws an error and it is not captured by the known errors, it will default to throwing a APIError.

import { Financeable } from "@financeable/aggregation";
import { CommercialAssetType } from "@financeable/aggregation/models/components";
import {
  ResponseBody,
  SDKValidationError,
} from "@financeable/aggregation/models/errors";

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

async function run() {
  let result;
  try {
    result = await financeable.applications.create({
      data: {
        type: "applications",
        attributes: {
          purpose: "Purchase of a motor vehicle",
          applicationType: "consumer",
        },
        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",
              },
            },
          },
          entities: {
            data: [
              {
                type: "entities",
                attributes: {
                  businessNames: [
                    "<value>",
                    "<value>",
                  ],
                  entityName: "<value>",
                  abn: "<value>",
                  acn: "<value>",
                  state: "QLD",
                  entityType: "Australian Private Company",
                },
              },
            ],
          },
          customers: {
            data: [
              {
                type: "customers",
                attributes: {
                  title: "Mr",
                  firstName: "John",
                  lastName: "Smith",
                  dateOfBirth: "01-01-1990",
                  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,
                        },
                      },
                    ],
                  },
                },
              },
            ],
          },
          asset: {
            data: {
              type: "assets",
              attributes: {
                ageOfAsset: 3,
                ageOfAssetAtEnd: 8,
                condition: "USED",
                assetType: CommercialAssetType.MotorVehicleLessThan45Tonnes,
                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",
              },
            },
          },
        },
      },
    });

    // 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 ResponseBody): {
        // Handle err.data$: ResponseBodyData
        console.error(err);
        return;
      }
      default: {
        // Other errors such as network errors, see HTTPClientErrors for more details
        throw err;
      }
    }
  }
}

run();

Validation errors can also occur when either method arguments or data returned from the server do not match the expected format. The SDKValidationError that is thrown as a result will capture the raw value that failed validation in an attribute called rawValue. Additionally, a pretty() method is available on this error that can be used to log a nicely formatted multi-line string since validation errors can list many issues and the plain error string may be difficult read when debugging.

In some rare cases, the SDK can fail to get a response from the server or even make the request due to unexpected circumstances such as network conditions. These types of errors are captured in the models/errors/httpclienterrors.ts module:

HTTP Client ErrorDescription
RequestAbortedErrorHTTP request was aborted by the client
RequestTimeoutErrorHTTP request timed out due to an AbortSignal signal
ConnectionErrorHTTP client was unable to make a request to a server
InvalidRequestErrorAny input used to create a request is invalid
UnexpectedClientErrorUnrecognised or unexpected error

Custom HTTP Client

The TypeScript SDK makes API calls using an HTTPClient that wraps the native 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:

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 });

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.

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.

FAQs

Package last updated on 31 Mar 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts