@backstage/backend-defaults
Version:
Backend defaults used by Backstage backend apps
91 lines (87 loc) • 2.58 kB
JavaScript
;
var errors = require('@backstage/errors');
class DefaultActionsService {
constructor(discovery, config, logger, auth) {
this.discovery = discovery;
this.config = config;
this.logger = logger;
this.auth = auth;
}
static create({
discovery,
config,
logger,
auth
}) {
return new DefaultActionsService(discovery, config, logger, auth);
}
async list({ credentials }) {
const pluginSources = this.config.getOptionalStringArray("backend.actions.pluginSources") ?? [];
const remoteActionsList = await Promise.all(
pluginSources.map(async (source) => {
try {
const response = await this.makeRequest({
path: `/.backstage/actions/v1/actions`,
pluginId: source,
credentials
});
if (!response.ok) {
throw await errors.ResponseError.fromResponse(response);
}
const { actions } = await response.json();
return actions;
} catch (error) {
this.logger.warn(`Failed to fetch actions from ${source}`, error);
return [];
}
})
);
return { actions: remoteActionsList.flat() };
}
async invoke(opts) {
const pluginId = this.pluginIdFromActionId(opts.id);
const response = await this.makeRequest({
path: `/.backstage/actions/v1/actions/${encodeURIComponent(
opts.id
)}/invoke`,
pluginId,
credentials: opts.credentials,
options: {
method: "POST",
body: JSON.stringify(opts.input),
headers: {
"Content-Type": "application/json"
}
}
});
if (!response.ok) {
throw await errors.ResponseError.fromResponse(response);
}
const { output } = await response.json();
return { output };
}
async makeRequest(opts) {
const { path, pluginId, credentials, options } = opts;
const baseUrl = await this.discovery.getBaseUrl(pluginId);
const { token } = await this.auth.getPluginRequestToken({
onBehalfOf: credentials,
targetPluginId: opts.pluginId
});
return fetch(`${baseUrl}${path}`, {
...options,
headers: {
...options?.headers,
Authorization: `Bearer ${token}`
}
});
}
pluginIdFromActionId(id) {
const colonIndex = id.indexOf(":");
if (colonIndex === -1) {
throw new Error(`Invalid action id: ${id}`);
}
return id.substring(0, colonIndex);
}
}
exports.DefaultActionsService = DefaultActionsService;
//# sourceMappingURL=DefaultActionsService.cjs.js.map