hrms-mgt/src/stores/structureTree.ts
2024-09-05 10:54:04 +07:00

77 lines
2.7 KiB
TypeScript

import { defineStore } from "pinia";
import { ref } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import type { DataStructureTree } from "@/interface/main";
const $q = useQuasar();
const { showLoader, hideLoader, messageError } = useCounterMixin();
export const useStructureTree = defineStore("structureTree", () => {
const activeId = ref<string>("");
const dataStore = ref<{ [key: string]: DataStructureTree[] }>({});
/**
* fetch ข้อมูลโครงสร้างตามคีย์ของระบบ
* @param sysKey คีย์ของระบบ
* @param isLoad สถานะที่ใช้ในการแสดงตัวโหลด true = แสดง, false = ไม่แสดง
* @returns ข้อมูลโครงสร้าง
*/
async function fetchStructureTree(sysKey: string, isLoad: boolean = false) {
if (dataStore.value[sysKey]) {
return dataStore.value[sysKey] || [];
} else {
activeId.value === "" && (await fetchActive());
const data = await fetchData(sysKey, isLoad);
return data || [];
}
}
/**
* fetch ข้อมูลโครงสร้างองค์กรปัจจุบัน
*
* เช็ต activeId.value เป็นค่า data.activeId ที่ได้จากข้อมูลที่ดึงมา
*/
async function fetchActive() {
try {
const res = await http.get(config.API.activeOrganization);
const data = res.data.result;
activeId.value = data.activeId;
} catch (err) {
messageError($q, err);
}
}
/**
* fetch ข้อมูลโครงสร้างจาก API
* @param sysKey คีย์ของระบบ
* @param isLoad สถานะที่ใช้ในการแสดงตัวโหลด true = แสดง, false = ไม่แสดง
* @returns ข้อมูลโครงสร้าง
*
* เมื่อ isLoad เป็น true จะทำการแสดงตัวโหลด showLoader
* และเก็บค่าใน dataStore.value ตามคีย์ของระบบที่รับมา
*/
async function fetchData(sysKey: string, isLoad: boolean) {
isLoad && showLoader();
try {
const res = await http.get(
config.API.orgByIdSystem(activeId.value, sysKey)
);
const data = res.data.result;
dataStore.value[sysKey] = data;
return data;
} catch (err) {
messageError($q, err);
} finally {
hideLoader();
}
}
return {
fetchStructureTree,
};
});