@coder/backstage-plugin-coder
Version:
Create and manage Coder workspaces from Backstage
77 lines (74 loc) • 2.9 kB
JavaScript
import { createApiRef } from '@backstage/core-plugin-api';
import { CODER_API_REF_ID_PREFIX } from '../typesConstants.esm.js';
import { StateSnapshotManager } from '../utils/StateSnapshotManager.esm.js';
const CODER_PROXY_PREFIX = "/coder";
const BASE_URL_KEY_FOR_CONFIG_API = "backend.baseUrl";
const PROXY_URL_KEY_FOR_DISCOVERY_API = "proxy";
const defaultUrlPrefixes = {
proxyPrefix: `/api/proxy`
};
const proxyRouteReplacer = /\/api\/proxy.*?$/;
class UrlSync {
discoveryApi;
urlCache;
urlPrefixes;
constructor(setup) {
const { apis, urlPrefixes = {} } = setup;
const { discoveryApi, configApi } = apis;
this.discoveryApi = discoveryApi;
this.urlPrefixes = { ...defaultUrlPrefixes, ...urlPrefixes };
const proxyRoot = this.getProxyRootFromConfigApi(configApi);
this.urlCache = new StateSnapshotManager({
initialSnapshot: this.prepareNewSnapshot(proxyRoot)
});
}
// ConfigApi is literally only used because it offers a synchronous way to
// get an initial URL to use from inside the constructor. Should not be used
// beyond initial constructor call, so it's not being embedded in the class
getProxyRootFromConfigApi(configApi) {
const baseUrl = configApi.getString(BASE_URL_KEY_FOR_CONFIG_API);
return `${baseUrl}${this.urlPrefixes.proxyPrefix}`;
}
prepareNewSnapshot(newProxyUrl) {
return {
baseUrl: newProxyUrl.replace(proxyRouteReplacer, ""),
assetsRoute: `${newProxyUrl}${CODER_PROXY_PREFIX}`,
apiRoute: `${newProxyUrl}${CODER_PROXY_PREFIX}`
};
}
/* ***************************************************************************
* All public functions should be defined as arrow functions to ensure they
* can be passed around React without risk of losing their `this` context
****************************************************************************/
getApiEndpoint = async () => {
const proxyRoot = await this.discoveryApi.getBaseUrl(
PROXY_URL_KEY_FOR_DISCOVERY_API
);
const newSnapshot = this.prepareNewSnapshot(proxyRoot);
this.urlCache.updateSnapshot(newSnapshot);
return newSnapshot.apiRoute;
};
getAssetsEndpoint = async () => {
const proxyRoot = await this.discoveryApi.getBaseUrl(
PROXY_URL_KEY_FOR_DISCOVERY_API
);
const newSnapshot = this.prepareNewSnapshot(proxyRoot);
this.urlCache.updateSnapshot(newSnapshot);
return newSnapshot.assetsRoute;
};
getCachedUrls = () => {
return this.urlCache.getSnapshot();
};
unsubscribe = (callback) => {
this.urlCache.unsubscribe(callback);
};
subscribe = (callback) => {
this.urlCache.subscribe(callback);
return () => this.unsubscribe(callback);
};
}
const urlSyncApiRef = createApiRef({
id: `${CODER_API_REF_ID_PREFIX}.url-sync`
});
export { CODER_PROXY_PREFIX, UrlSync, defaultUrlPrefixes, urlSyncApiRef };
//# sourceMappingURL=UrlSync.esm.js.map