service-titan-api
Version:
A module for authenticating and accessing the ServiceTitan API.
53 lines (47 loc) • 2.11 kB
JavaScript
// src/businessUnits/getBusinessUnits.mjs
import axios from "axios";
/**
* Retrieves a list of business units from the ServiceTitan API.
*
* @param {Object} options
* @param {ServiceTitanAuth} options.auth - An instance of ServiceTitanAuth
* @param {string} options.appKey - Your ServiceTitan Application Key
* @param {number} options.tenant - Your Tenant ID
* @param {Object} [options.params={}] - Optional query parameters (e.g., ids, name, active, page, pageSize, includeTotal, createdBefore, createdOnOrAfter, modifiedBefore, modifiedOnOrAfter, externalDataApplicationGuid)
* @returns {Promise<Object>} Parsed JSON response from the API.
*/
export async function getBusinessUnits({ auth, appKey, tenant, params = {} }) {
if (!auth) throw new Error("An instance of ServiceTitanAuth is required");
if (!appKey) throw new Error("appKey is required for resource API calls");
if (!tenant) throw new Error("tenant is required for API calls");
const token = await auth.getAccessToken();
// Determine the base URL based on the environment in auth.
const baseUrl =
auth.environment === "integration"
? `https://api-integration.servicetitan.io/settings/v2/tenant/${tenant}/business-units`
: `https://api.servicetitan.io/settings/v2/tenant/${tenant}/business-units`;
// Build query string from provided parameters.
const queryString = new URLSearchParams(params).toString();
const url = queryString ? `${baseUrl}?${queryString}` : baseUrl;
try {
const response = await axios.get(url, {
headers: {
Authorization: token,
"ST-App-Key": appKey,
"Content-Type": "application/json",
},
});
return response.data;
} catch (error) {
const status = error.response ? error.response.status : "Unknown status";
const statusText = error.response
? error.response.statusText
: "Unknown error";
const errorData = error.response
? JSON.stringify(error.response.data)
: error.message;
throw new Error(
`Error fetching business units: ${status} ${statusText}: ${errorData}`
);
}
}