@fireflyai/backstage-backend-plugin-firefly
Version:
Firefly backend plugin for Backstage
118 lines (112 loc) • 3.36 kB
JavaScript
;
var axios = require('axios');
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
var axios__default = /*#__PURE__*/_interopDefaultCompat(axios);
class FireflyClient {
baseUrl = "https://api.firefly.ai/api/v1.0";
accessKey;
secretKey;
accessToken = "";
logger;
constructor(config) {
this.accessKey = config.accessKey;
this.secretKey = config.secretKey;
this.logger = config.logger;
}
/**
* Authenticates with the Firefly API and obtains an access token
*/
async login() {
try {
const response = await axios__default.default.post(`${this.baseUrl}/login`, {
accessKey: this.accessKey,
secretKey: this.secretKey
}, {
headers: {
"Content-Type": "application/json"
}
});
if (!response.data.accessToken) {
throw new Error("No access token received from login");
}
this.accessToken = response.data.accessToken;
return this.accessToken;
} catch (error) {
if (axios__default.default.isAxiosError(error)) {
throw new Error(`Login failed: ${error.response?.status} - ${error}`);
}
throw error;
}
}
/**
* Makes an authenticated request to the Firefly API
*/
async request(path, method = "GET", data) {
if (!this.accessToken) {
await this.login();
}
if (!this.accessToken) {
throw new Error("Failed to obtain access token");
}
const response = await axios__default.default({
method,
url: `${this.baseUrl}${path}`,
data,
headers: {
"Authorization": `Bearer ${this.accessToken}`,
"Content-Type": "application/json"
}
});
if (response.status === 401) {
await this.login();
return this.request(path, method, data);
}
return response.data;
}
/**
* Retrieves a list of assets based on the provided filters
*/
async getAssets(filters) {
const response = await this.request("/inventory", "POST", filters);
return response;
}
/**
* Retrieves a list of all assets based on the provided filters
*/
async getAllAssets(filters, pageSize = 1e4) {
this.logger.info("Getting all assets");
const assets = [];
let hasMore = true;
let page = 1;
let afterKey;
while (hasMore) {
let retries = 0;
let response;
while (retries < 3) {
try {
response = await this.getAssets({ ...filters, size: pageSize, afterKey });
break;
} catch (error) {
retries++;
if (retries === 3) {
throw error;
}
this.logger.warn(`Failed to get assets, attempt ${retries} of 3`);
const timeout = 1e3 * retries;
await new Promise((resolve) => setTimeout(resolve, timeout));
}
}
if (!response) {
throw new Error("Failed to get assets");
}
this.logger.info(`Found ${response.responseObjects.length} assets on page ${page}, total objects: ${response.totalObjects}`);
assets.push(...response.responseObjects);
hasMore = response.responseObjects.length === pageSize;
afterKey = response.afterKey;
page++;
}
return assets;
}
}
exports.FireflyClient = FireflyClient;
//# sourceMappingURL=fireflyClient.cjs.js.map