From d335edd3cadfb17dfcd75f4a15b320d9e8d2bbea Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Wed, 3 Apr 2024 10:38:09 +0700 Subject: [PATCH] feat: fetch address from api --- src/stores/address/index.ts | 90 +++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 src/stores/address/index.ts diff --git a/src/stores/address/index.ts b/src/stores/address/index.ts new file mode 100644 index 00000000..da89566e --- /dev/null +++ b/src/stores/address/index.ts @@ -0,0 +1,90 @@ +import { ref } from 'vue'; +import { defineStore } from 'pinia'; +import { api } from 'src/boot/axios'; + +export interface SubDistrict { + updatedAt: string; + updateBy: string; + createdAt: string; + createdBy: string; + districtId: string; + zipCode: string; + nameEN: string; + nameTH: string; + id: string; +} + +export interface District { + updatedAt: string; + updateBy: string; + createdAt: string; + createdBy: string; + provinceId: string; + nameEN: string; + nameTH: string; + id: string; +} + +export interface Province { + updatedAt: string; + updateBy: string; + createdAt: string; + createdBy: string; + nameEN: string; + nameTH: string; + id: string; +} + +const useAddressStore = defineStore('api-address', () => { + const province = ref(); + const district = ref>({}); + const subDistrict = ref>({}); + + async function fetchProvince() { + if (province.value) return province.value; + + const res = await api.get(`/address/province`); + + if (!res) return false; + + province.value = res.data; + + return province.value; + } + + async function fetchDistrictByProvinceId(provinceId: string) { + if (district.value[provinceId]) return district.value[provinceId]; + + const res = await api.get( + `/address/province/${provinceId}/district`, + ); + + if (!res) return false; + + district.value[provinceId] = res.data; + + return district.value[provinceId]; + } + + async function fetchSubDistrictByProvinceId(districtId: string) { + if (subDistrict.value[districtId]) return subDistrict.value[districtId]; + + const res = await api.get( + `/address/district/${districtId}/sub-district`, + ); + + if (!res) return false; + + subDistrict.value[districtId] = res.data; + + return subDistrict.value[districtId]; + } + + return { + fetchProvince, + fetchDistrictByProvinceId, + fetchSubDistrictByProvinceId, + }; +}); + +export default useAddressStore;