Skip to content

Commit

Permalink
Replace fetcher in api/histories.archived.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
davelopez committed Jul 23, 2024
1 parent aab78c0 commit 2f84034
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 107 deletions.
98 changes: 23 additions & 75 deletions client/src/api/histories.archived.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import type { FetchArgType } from "openapi-typescript-fetch";

import { type components, fetcher } from "@/api/schema";
import { client, type components, GalaxyApiPaths } from "@/api/schema";
import { rethrowSimple } from "@/utils/simple-error";

export type ArchivedHistorySummary = components["schemas"]["ArchivedHistorySummary"];
export type ArchivedHistoryDetailed = components["schemas"]["ArchivedHistoryDetailed"];
export type AnyArchivedHistory = ArchivedHistorySummary | ArchivedHistoryDetailed;
export type AsyncTaskResultSummary = components["schemas"]["AsyncTaskResultSummary"];

type GetArchivedHistoriesParams = FetchArgType<typeof getArchivedHistories>;
type SerializationOptions = Pick<GetArchivedHistoriesParams, "view" | "keys">;
type MaybeArchivedHistoriesQueryParams = GalaxyApiPaths["/api/histories/archived"]["get"]["parameters"]["query"];
type ArchivedHistoriesQueryParams = Exclude<MaybeArchivedHistoriesQueryParams, undefined>;
type SerializationOptions = Pick<ArchivedHistoriesQueryParams, "view" | "keys">;

interface FilterOptions {
query?: string;
Expand All @@ -26,97 +27,44 @@ interface SortingOptions {
interface GetArchivedHistoriesOptions extends FilterOptions, PaginationOptions, SortingOptions, SerializationOptions {}

interface ArchivedHistoriesResult {
histories: ArchivedHistorySummary[] | ArchivedHistoryDetailed[];
histories: AnyArchivedHistory[];
totalMatches: number;
}

const DEFAULT_PAGE_SIZE = 10;

const getArchivedHistories = fetcher.path("/api/histories/archived").method("get").create();

/**
* Get a list of archived histories.
*/
export async function fetchArchivedHistories(
options: GetArchivedHistoriesOptions = {}
): Promise<ArchivedHistoriesResult> {
export async function fetchArchivedHistories(options: GetArchivedHistoriesOptions): Promise<ArchivedHistoriesResult> {
const params = optionsToApiParams(options);
const { data, headers } = await getArchivedHistories(params);
const totalMatches = parseInt(headers.get("total_matches") ?? "0");

const { response, data, error } = await client.GET("/api/histories/archived", {
params: {
query: params,
},
});

if (error) {
rethrowSimple(error);
}

const totalMatches = parseInt(response.headers.get("total_matches") ?? "0");
if (params.view === "detailed") {
return {
histories: data as ArchivedHistoryDetailed[],
totalMatches,
};
}

return {
histories: data as ArchivedHistorySummary[],
totalMatches,
};
}

const postArchiveHistory = fetcher.path("/api/histories/{history_id}/archive").method("post").create();

/**
* Archive a history.
* @param historyId The history to archive
* @param archiveExportId The optional archive export record to associate. This can be used to restore a snapshot copy of the history in the future.
* @param purgeHistory Whether to purge the history after archiving. Can only be used in combination with an archive export record.
* @returns The archived history summary.
*/
export async function archiveHistory(
historyId: string,
archiveExportId?: string,
purgeHistory?: boolean
): Promise<ArchivedHistorySummary> {
const { data } = await postArchiveHistory({
history_id: historyId,
archive_export_id: archiveExportId,
purge_history: purgeHistory,
});
return data as ArchivedHistorySummary;
}

const putUnarchiveHistory = fetcher
.path("/api/histories/{history_id}/archive/restore")
.method("put")
// @ts-ignore: workaround for optional query parameters in PUT. More info here https://github.com/ajaishankar/openapi-typescript-fetch/pull/55
.create({ force: undefined });

/**
* Unarchive/restore a history.
* @param historyId The history to unarchive.
* @param force Whether to force un-archiving for purged histories.
* @returns The restored history summary.
*/
export async function unarchiveHistory(historyId: string, force?: boolean): Promise<ArchivedHistorySummary> {
const { data } = await putUnarchiveHistory({ history_id: historyId, force });
return data as ArchivedHistorySummary;
}

const reimportHistoryFromStore = fetcher.path("/api/histories/from_store_async").method("post").create();

/**
* Reimport an archived history as a new copy from the associated export record.
*
* @param archivedHistory The archived history to reimport. It must have an associated export record.
* @returns The async task result summary to track the reimport progress.
*/
export async function reimportArchivedHistoryFromExportRecord(
archivedHistory: ArchivedHistorySummary
): Promise<AsyncTaskResultSummary> {
if (!archivedHistory.export_record_data) {
throw new Error("The archived history does not have an associated export record.");
}
const { data } = await reimportHistoryFromStore({
model_store_format: archivedHistory.export_record_data.model_store_format,
store_content_uri: archivedHistory.export_record_data.target_uri,
});
return data as AsyncTaskResultSummary;
}

function optionsToApiParams(options: GetArchivedHistoriesOptions): GetArchivedHistoriesParams {
const params: GetArchivedHistoriesParams = {};
function optionsToApiParams(options: GetArchivedHistoriesOptions): ArchivedHistoriesQueryParams {
const params: ArchivedHistoriesQueryParams = {};
if (options.query) {
params.q = ["name-contains"];
params.qv = [options.query];
Expand Down
67 changes: 44 additions & 23 deletions client/src/components/History/Archiving/HistoryArchive.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@ import { BAlert, BListGroup, BListGroupItem, BPagination } from "bootstrap-vue";
import { computed, onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router/composables";
import {
ArchivedHistorySummary,
fetchArchivedHistories,
reimportArchivedHistoryFromExportRecord,
} from "@/api/histories.archived";
import { client } from "@/api";
import { type ArchivedHistorySummary, fetchArchivedHistories } from "@/api/histories.archived";
import { useConfirmDialog } from "@/composables/confirmDialog";
import { useToast } from "@/composables/toast";
import { useHistoryStore } from "@/stores/historyStore";
import localize from "@/utils/localization";
import { errorMessageAsString } from "@/utils/simple-error";
import DelayedInput from "@/components/Common/DelayedInput.vue";
import ArchivedHistoryCard from "@/components/History/Archiving/ArchivedHistoryCard.vue";
Expand Down Expand Up @@ -50,16 +48,24 @@ async function updateSearchQuery(query: string) {
async function loadArchivedHistories() {
isLoading.value = true;
const result = await fetchArchivedHistories({
query: searchText.value,
currentPage: currentPage.value,
pageSize: perPage.value,
sortBy: sortBy.value,
sortDesc: sortDesc.value,
});
totalRows.value = result.totalMatches;
archivedHistories.value = result.histories;
isLoading.value = false;
try {
const result = await fetchArchivedHistories({
query: searchText.value,
currentPage: currentPage.value,
pageSize: perPage.value,
sortBy: sortBy.value,
sortDesc: sortDesc.value,
});
totalRows.value = result.totalMatches;
archivedHistories.value = result.histories;
} catch (error) {
toast.error(
localize(`Failed to load archived histories with reason: ${errorMessageAsString(error)}`),
localize("Loading Failed")
);
} finally {
isLoading.value = false;
}
}
function onViewHistoryInCenterPanel(history: ArchivedHistorySummary) {
Expand Down Expand Up @@ -110,20 +116,35 @@ async function onImportCopy(history: ArchivedHistorySummary) {
return;
}
try {
await reimportArchivedHistoryFromExportRecord(history);
toast.success(
localize(
`The History '${history.name}' it's being imported. This process may take a while. Check your histories list after a few minutes.`
),
localize("Importing History in background...")
if (!history.export_record_data) {
toast.error(
localize(`Failed to import history '${history.name}' because it does not have an export record.`),
localize("History Import Failed")
);
} catch (error) {
return;
}
const { error } = await client.POST("/api/histories/from_store_async", {
body: {
model_store_format: history.export_record_data?.model_store_format,
store_content_uri: history.export_record_data?.target_uri,
},
});
if (error) {
toast.error(
localize(`Failed to import history '${history.name}' with reason: ${error}`),
localize("History Import Failed")
);
return;
}
toast.success(
localize(
`The History '${history.name}' it's being imported. This process may take a while. Check your histories list after a few minutes.`
),
localize("Importing History in background...")
);
}
</script>
<template>
Expand Down
45 changes: 36 additions & 9 deletions client/src/stores/historyStore.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { defineStore } from "pinia";
import { computed, del, ref, set } from "vue";

import type {
AnyHistory,
HistoryContentsStats,
HistoryDevDetailed,
HistorySummary,
HistorySummaryExtended,
import {
type AnyHistory,
client,
type HistoryContentsStats,
type HistoryDevDetailed,
type HistorySummary,
type HistorySummaryExtended,
} from "@/api";
import { historyFetcher } from "@/api/histories";
import { archiveHistory, unarchiveHistory } from "@/api/histories.archived";
import { type ArchivedHistoryDetailed } from "@/api/histories.archived";
import { HistoryFilters } from "@/components/History/HistoryFilters";
import { useUserLocalStorage } from "@/composables/userLocalStorage";
import {
Expand Down Expand Up @@ -288,11 +289,26 @@ export const useHistoryStore = defineStore("historyStore", () => {
}

async function archiveHistoryById(historyId: string, archiveExportId?: string, purgeHistory = false) {
const history = await archiveHistory(historyId, archiveExportId, purgeHistory);
const { data, error } = await client.POST("/api/histories/{history_id}/archive", {
params: {
path: { history_id: historyId },
},
body: {
archive_export_id: archiveExportId,
purge_history: purgeHistory,
},
});

if (error) {
rethrowSimple(error);
}

const history = data as ArchivedHistoryDetailed;
setHistory(history);
if (!history.archived) {
return;
}

// If the current history is archived, we need to switch to another one as it is
// no longer part of the active histories.
const nextHistoryId = getNextAvailableHistoryId([historyId]);
Expand All @@ -304,7 +320,18 @@ export const useHistoryStore = defineStore("historyStore", () => {
}

async function unarchiveHistoryById(historyId: string, force?: boolean) {
const history = await unarchiveHistory(historyId, force);
const { data, error } = await client.PUT("/api/histories/{history_id}/archive/restore", {
params: {
path: { history_id: historyId },
query: { force },
},
});

if (error) {
rethrowSimple(error);
}

const history = data as ArchivedHistoryDetailed;
setHistory(history);
return history;
}
Expand Down

0 comments on commit 2f84034

Please sign in to comment.