2023-10-09 17:21:27 -04:00
|
|
|
import { debounce } from "lodash-es";
|
2023-10-11 16:38:20 -04:00
|
|
|
import { message } from "ant-design-vue";
|
2023-12-20 17:23:31 -05:00
|
|
|
import { IStory } from "@models/stories";
|
2023-10-09 17:21:27 -04:00
|
|
|
import { useAutoSaveStore } from "~/stores/autosaveStore";
|
|
|
|
|
2023-12-29 19:47:21 -05:00
|
|
|
export const autoSave = async (values: any) => {
|
2023-10-09 17:21:27 -04:00
|
|
|
const store = useAutoSaveStore();
|
2023-10-12 22:56:09 -04:00
|
|
|
const fid = store.$state.fetchId;
|
|
|
|
if (store.$state.fetchId !== fid) return;
|
|
|
|
store.$patch({ fetchId: store.$state.fetchId + 1 });
|
2023-10-09 17:21:27 -04:00
|
|
|
if (store.$state.draftId == undefined) {
|
2023-12-30 17:20:32 -05:00
|
|
|
let { data, error } = await useApiFetch<{ draftId: number; success: boolean }>("/drafts/new", {
|
2023-10-09 17:21:27 -04:00
|
|
|
method: "post",
|
|
|
|
body: values,
|
|
|
|
});
|
2023-12-30 17:20:32 -05:00
|
|
|
console.log("fibberty", data, error);
|
|
|
|
if (data.value) {
|
|
|
|
store.$patch({ draftId: data.value.draftId });
|
|
|
|
}
|
2023-10-09 17:21:27 -04:00
|
|
|
} else {
|
2023-12-30 17:20:32 -05:00
|
|
|
await useApiFetch<any>(`/drafts/${store.$state.draftId}`, {
|
2023-10-09 17:21:27 -04:00
|
|
|
method: "put",
|
|
|
|
body: values,
|
|
|
|
});
|
|
|
|
}
|
2023-12-29 19:47:21 -05:00
|
|
|
};
|
2023-10-11 16:38:20 -04:00
|
|
|
|
2023-12-30 17:20:32 -05:00
|
|
|
export const autoEdit = async (values: any, endpoint: string, method: "put" | "post") => {
|
|
|
|
const [messageApi] = message.useMessage();
|
|
|
|
const { data, error } = await useApiFetch<{ success: boolean; data: IStory }>(endpoint, {
|
2023-12-29 19:47:21 -05:00
|
|
|
method,
|
|
|
|
body: values,
|
|
|
|
});
|
2023-12-30 17:20:32 -05:00
|
|
|
if (data.value?.success) {
|
|
|
|
messageApi.success("Your work has been saved successfully.");
|
|
|
|
} else if (error) {
|
|
|
|
messageApi.error("Error saving data.");
|
|
|
|
}
|
2023-12-29 19:47:21 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
export const debouncedAutoEdit = debounce(autoEdit, 5000);
|
|
|
|
export const debouncedAutoSave = debounce(autoSave, 10000);
|