@financeable/aggregation
v0.15.2
Published
<!-- Start Summary [summary] --> ## Summary
Readme
financeable-aggregation-api
Summary
Table of Contents
SDK Installation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add @financeable/aggregationPNPM
pnpm add @financeable/aggregationBun
bun add @financeable/aggregationYarn
yarn add @financeable/aggregationRequirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
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: "[email protected]"
},
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: '[email protected]',
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: [
"[email protected]",
],
phoneNumbers: [
"0412345678",
],
},
},
{
type: "entities",
attributes: {
entityName: "Financeable Pty Ltd",
abn: "12345678901",
turnover: 1000000,
industryType: "Finance",
emails: [
"[email protected]",
],
phoneNumbers: [
"0412345678",
],
},
},
{
type: "entities",
attributes: {
entityName: "Financeable Pty Ltd",
abn: "12345678901",
turnover: 1000000,
industryType: "Finance",
emails: [
"[email protected]",
],
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();
Available Resources and Operations
Applications
- create - Create an application in the Financeable platform.
- 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 - Retrieve a specific application from the Financeable platform.
OauthToken
- get - Obtain an OAuth client_credentials token
SupportingDocuments
- create - Create a supporting document record in Financeable, and returns a pre-signed URL to upload this document with.
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.
applicationsCreate- Create an application in the Financeable platform.applicationsGet- Retrieve a specific application from the Financeable platform.applicationsList- 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- Obtain an OAuth client_credentials tokensupportingDocumentsCreate- Create a supporting document record in Financeable, and returns a pre-signed URL to upload this document with.
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({
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: "[email protected]",
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:
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: "[email protected]",
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();
Error Handling
FinanceableError 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
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: "[email protected]",
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: The base class for HTTP error responses.
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from FinanceableError:
ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
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: 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.
