@spacelift-io/backstage-integration-backend
Version:
Backstage plugin for integrating Spacelift.io with Backstage
110 lines (106 loc) • 3.3 kB
JavaScript
;
var graphqlRequest = require('graphql-request');
var validations = require('../../helpers/validations.cjs.js');
async function createSpaceliftService({
api,
logger
}) {
const apiUrl = `https://${api.hostUrl}/graphql`;
let apiToken = null;
let tokenExpiry = null;
const getToken = async () => {
if (apiToken && tokenExpiry && /* @__PURE__ */ new Date() < tokenExpiry) {
logger.info("Using cached API token");
return apiToken;
}
if (apiToken && tokenExpiry && /* @__PURE__ */ new Date() >= tokenExpiry) {
logger.info("Cached API token expired, clearing cache");
apiToken = null;
tokenExpiry = null;
}
logger.info("Fetching new API token");
const getSpaceliftTokenMutation = graphqlRequest.gql`
mutation GetSpaceliftToken($apiKey: ID!, $apiSecret: String!) {
apiKeyUser(id: $apiKey, secret: $apiSecret) {
id
jwt
}
}
`;
try {
const response = await graphqlRequest.request(
apiUrl,
getSpaceliftTokenMutation,
{
apiKey: api.apiKey,
apiSecret: api.apiSecret
}
);
apiToken = response.apiKeyUser.jwt;
tokenExpiry = new Date((/* @__PURE__ */ new Date()).getTime() + 60 * 1e3);
logger.info("New API token fetched and cached");
return apiToken;
} catch (error) {
logger.error("Error fetching JWT:", error);
apiToken = null;
tokenExpiry = null;
throw new Error(
`Failed to authenticate with Spacelift API: ${error instanceof Error ? error.message : "Unknown error"}`
);
}
};
return {
getStacks: async () => {
const currentToken = await getToken();
const stacksQuery = graphqlRequest.gql`
query GetStacks () {
stacks {
id
name,
description,
labels,
state,
branch,
spaceDetails {
id
name
}
}
}
`;
logger.info("Fetching stacks");
const rawResponse = await graphqlRequest.request(
apiUrl,
stacksQuery,
{},
{ Authorization: `Bearer ${currentToken}` }
);
const validationResult = validations.validateStacks(rawResponse.stacks);
logger.info("Stacks fetched and validated successfully \u{1F389}");
return validationResult;
},
triggerRun: async (stackId) => {
const currentToken = await getToken();
const triggerRunMutation = graphqlRequest.gql`
mutation TriggerRun($stackId: ID!) {
runTrigger(stack: $stackId) {
id
state
}
}
`;
logger.info(`Triggering run for stack ${stackId}`);
const rawResponse = await graphqlRequest.request(
apiUrl,
triggerRunMutation,
{ stackId },
{ Authorization: `Bearer ${currentToken}` }
);
const validationResult = validations.validateTriggerRunResult(rawResponse.runTrigger);
logger.info(`Run triggered and validated successfully for stack ${stackId} \u{1F389}`);
return validationResult;
}
};
}
exports.createSpaceliftService = createSpaceliftService;
//# sourceMappingURL=Spacelift.service.cjs.js.map