next/lib/client/utils.ts

43 lines
1.3 KiB
TypeScript
Raw Permalink Normal View History

import { debounce } from "lodash-es";
import { message } from "ant-design-vue";
import { IStory } from "@models/stories";
import { useAutoSaveStore } from "~/stores/autosaveStore";
export const autoSave = async (values: any) => {
const store = useAutoSaveStore();
const fid = store.$state.fetchId;
if (store.$state.fetchId !== fid) return;
store.$patch({ fetchId: store.$state.fetchId + 1 });
if (store.$state.draftId == undefined) {
let { data, error } = await useApiFetch<{ draftId: number; success: boolean }>("/drafts/new", {
method: "post",
body: values,
});
console.log("fibberty", data, error);
if (data.value) {
store.$patch({ draftId: data.value.draftId });
}
} else {
await useApiFetch<any>(`/drafts/${store.$state.draftId}`, {
method: "put",
body: values,
});
}
};
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, {
method,
body: values,
});
if (data.value?.success) {
messageApi.success("Your work has been saved successfully.");
} else if (error) {
messageApi.error("Error saving data.");
}
};
export const debouncedAutoEdit = debounce(autoEdit, 5000);
export const debouncedAutoSave = debounce(autoSave, 10000);