1
0
Fork 0
mirror of https://github.com/mealie-recipes/mealie.git synced 2025-07-19 21:29:40 +02:00
mealie/frontend/composables/use-groups.ts

102 lines
2.3 KiB
TypeScript
Raw Normal View History

import { useUserApi } from "~/composables/api";
import type { GroupBase, GroupSummary } from "~/lib/api/types/user";
2024-03-15 19:41:26 +00:00
const groupSelfRef = ref<GroupSummary | null>(null);
2024-03-15 19:41:26 +00:00
const loading = ref(false);
export const useGroupSelf = function () {
const api = useUserApi();
2024-03-15 19:41:26 +00:00
async function refreshGroupSelf() {
loading.value = true;
const { data } = await api.groups.getCurrentUserGroup();
groupSelfRef.value = data;
loading.value = false;
}
const actions = {
get() {
2024-03-15 19:41:26 +00:00
if (!(groupSelfRef.value || loading.value)) {
refreshGroupSelf();
}
2024-03-15 19:41:26 +00:00
return groupSelfRef;
},
async updatePreferences() {
2024-03-15 19:41:26 +00:00
if (!groupSelfRef.value) {
await refreshGroupSelf();
}
if (!groupSelfRef.value?.preferences) {
return;
}
2024-03-15 19:41:26 +00:00
const { data } = await api.groups.setPreferences(groupSelfRef.value.preferences);
if (data) {
2024-03-15 19:41:26 +00:00
groupSelfRef.value.preferences = data;
}
},
};
const group = actions.get();
return { actions, group };
};
export const useGroups = function () {
const api = useUserApi();
const loading = ref(false);
function getAllGroups() {
loading.value = true;
const asyncKey = String(Date.now());
const { data: groups } = useAsyncData(asyncKey, async () => {
const { data } = await api.groups.getAll(1, -1, { orderBy: "name", orderDirection: "asc" }); ;
if (data) {
return data.items;
}
else {
return null;
}
});
loading.value = false;
return groups;
}
async function refreshAllGroups() {
loading.value = true;
const { data } = await api.groups.getAll(1, -1, { orderBy: "name", orderDirection: "asc" }); ;
if (data) {
groups.value = data.items;
}
else {
groups.value = null;
}
loading.value = false;
}
async function deleteGroup(id: string | number) {
loading.value = true;
const { data } = await api.groups.deleteOne(id);
loading.value = false;
refreshAllGroups();
return data;
}
2022-05-21 21:22:02 +02:00
async function createGroup(payload: GroupBase) {
loading.value = true;
const { data } = await api.groups.createOne(payload);
if (data && groups.value) {
groups.value.push(data);
}
}
const groups = getAllGroups();
return { groups, getAllGroups, refreshAllGroups, deleteGroup, createGroup };
};