Refactor api

Signed-off-by: Niek Rossen <niek.rossen@infosupport.com>
This commit is contained in:
Niek Rossen
2024-03-18 15:22:40 +01:00
parent 2468e96d89
commit 4f996b3d94
+23 -58
View File
@@ -117,74 +117,19 @@ export class OctopusDeployClient implements OctopusDeployApi {
releaseHistoryCount: number;
}): Promise<OctopusProgression> {
const url = await this.getProgressionApiUrl(opts);
const response = await this.fetchApi.fetch(url);
let responseJson;
try {
responseJson = await response.json();
} catch (e) {
responseJson = { releases: [] };
}
if (response.status !== 200) {
throw new Error(
`Error communicating with Octopus Deploy: ${
responseJson?.error?.title || response.statusText
}`,
);
}
return responseJson;
return this.fetchAndHandleErrors(url);
}
async getProjectInfo(
projectReference: ProjectReference,
): Promise<OctopusProject> {
const url = await this.getProjectApiUrl(projectReference);
const response = await this.fetchApi.fetch(url);
let responseJson;
try {
responseJson = await response.json();
} catch (e) {
responseJson = { releases: [] };
}
if (response.status !== 200) {
throw new Error(
`Error communicating with Octopus Deploy: ${
responseJson?.error?.title || response.statusText
}`,
);
}
return responseJson;
return this.fetchAndHandleErrors(url);
}
async getProjectGroups(): Promise<OctopusProjectGroup[]> {
const url = await this.getProjectGroupApiUrl();
const response = await this.fetchApi.fetch(url);
let responseJson;
try {
responseJson = await response.json();
} catch (e) {
responseJson = { releases: [] };
}
if (response.status !== 200) {
throw new Error(
`Error communicating with Octopus Deploy: ${
responseJson?.error?.title || response.statusText
}`,
);
}
return responseJson;
return this.fetchAndHandleErrors(url);
}
async getConfig(): Promise<OctopusPluginConfig> {
@@ -193,6 +138,26 @@ export class OctopusDeployClient implements OctopusDeployApi {
};
}
private async fetchAndHandleErrors<T>(url: string): Promise<T> {
const response = await this.fetchApi.fetch(url);
let responseJson: T;
try {
responseJson = await response.json();
} catch (e) {
throw new Error(`Failed to parse JSON response: ${e}`);
}
if (!response.ok) {
throw new Error(
`Error communicating with Octopus Deploy: ${response.status}`,
);
}
return responseJson;
}
private async getProgressionApiUrl(opts: {
projectReference: ProjectReference;
releaseHistoryCount: number;