mealie/frontend/composables/recipes/use-recipe-tools.ts
Hayden fcc5d99d40
chore: frontend testing setup (#1739)
* add vitest

* initialize lib w/ tests

* move to dev dep

* run tests in CI

* update file names

* move api folder to lib

* move api and api types to same folder

* update generator outpath

* rm husky

* i guess i _did_ need those types

* reorg types

* extract validators into testable components

* (WIP) start composable testing

* fix import type

* fix linter complaint

* simplify icon type def

* fix linter errors (maybe?)

* rename client file for sorting
2022-10-22 11:51:07 -08:00

102 lines
2.0 KiB
TypeScript

import { reactive, ref, useAsync } from "@nuxtjs/composition-api";
import { useAsyncKey } from "../use-utils";
import { useUserApi } from "~/composables/api";
import { VForm } from "~/types/vuetify";
import { RecipeTool } from "~/lib/api/types/user";
export const useTools = function (eager = true) {
const workingToolData = reactive<RecipeTool>({
id: "",
name: "",
slug: "",
onHand: false,
});
const api = useUserApi();
const loading = ref(false);
const validForm = ref(false);
const actions = {
getAll() {
loading.value = true;
const units = useAsync(async () => {
const { data } = await api.tools.getAll();
if (data) {
return data.items;
} else {
return null;
}
}, useAsyncKey());
loading.value = false;
return units;
},
async refreshAll() {
loading.value = true;
const { data } = await api.tools.getAll();
if (data) {
tools.value = data.items;
}
loading.value = false;
},
async createOne(domForm: VForm | null = null) {
if (domForm && !domForm.validate()) {
validForm.value = false;
}
loading.value = true;
const { data } = await api.tools.createOne(workingToolData);
if (data) {
tools.value?.push(data);
}
domForm?.reset();
this.reset();
},
async updateOne() {
loading.value = true;
const { data } = await api.tools.updateOne(workingToolData.id, workingToolData);
if (data) {
tools.value?.push(data);
}
this.reset();
},
async deleteOne(id: number) {
loading.value = true;
await api.tools.deleteOne(id);
this.reset();
},
reset() {
workingToolData.name = "";
workingToolData.id = "";
loading.value = false;
validForm.value = true;
},
};
const tools = (() => {
if (eager) {
return actions.getAll();
} else {
return ref([]);
}
})();
return {
tools,
actions,
workingToolData,
loading,
};
};