@spotable/attio-sdk
Version:
Client for Attio REST API
91 lines • 3.29 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchAttioSchema = fetchAttioSchema;
const node_fetch_1 = require("node-fetch");
const ora_1 = require("ora");
const logger_1 = require("./logger");
class HTTPResponseError extends Error {
constructor(response) {
super(`HTTP Error Response: ${response.status} ${response.statusText}`);
this.response = response;
this.response = response;
}
}
async function logError(error) {
if (error instanceof HTTPResponseError) {
const body = await error.response.json();
logger_1.default.error(`API error (${error.response.status}): ${JSON.stringify(body)}`);
}
else {
logger_1.default.error(`Error fetching schema`, { error });
}
}
async function checkStatus(response) {
if (response.ok) {
return response.json();
}
throw new HTTPResponseError(response);
}
async function fetchAttioObjects(apiKey) {
const fetchLoader = (0, ora_1.default)("Fetching Attio objects").start();
try {
const response = await (0, node_fetch_1.default)("https://api.attio.com/v2/objects", {
method: "GET",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
});
const body = await checkStatus(response);
if (!response.ok) {
logger_1.default.error(`Failed to fetch objects: ${response.statusText}`, {
response: body,
});
throw new Error(`Failed to fetch objects: ${response.statusText}`);
}
const objects = body.data;
fetchLoader.succeed(`Found ${objects.length} objects`);
return objects;
}
catch (error) {
fetchLoader.fail("Failed to fetch Attio objects");
await logError(error);
throw error;
}
}
async function fetchAttioAttributes(apiKey, object) {
const fetchLoader = (0, ora_1.default)(`Fetching attributes for ${object.singular_noun}`).start();
try {
const response = await (0, node_fetch_1.default)(`https://api.attio.com/v2/objects/${object.api_slug}/attributes`, {
method: "GET",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
});
const body = await checkStatus(response);
const attributes = body.data;
fetchLoader.succeed(`Found ${attributes.length} attributes for ${object.singular_noun}`);
return attributes;
}
catch (error) {
fetchLoader.fail(`Failed to fetch attributes for ${object.singular_noun}`);
await logError(error);
throw error;
}
}
async function fetchAttioSchema(apiKey) {
const fetchLoader = (0, ora_1.default)("Fetching Attio schema").start();
const objects = await fetchAttioObjects(apiKey);
const attributes = {};
for (const object of objects) {
const objectAttributes = await fetchAttioAttributes(apiKey, object);
attributes[object.api_slug] = objectAttributes;
}
fetchLoader.succeed("Attio schema fetched successfully");
return {
objects,
attributes,
};
}
//# sourceMappingURL=fetchAttioSchema.js.map