|
| 1 | +import { fetchDictList } from '@/service' |
| 2 | +import { session } from '@/utils' |
| 3 | + |
| 4 | +export const useDictStore = defineStore('dict-store', { |
| 5 | + state: () => { |
| 6 | + return { |
| 7 | + dictMap: {} as DictMap, |
| 8 | + isInitDict: false, |
| 9 | + } |
| 10 | + }, |
| 11 | + actions: { |
| 12 | + async dict(code: string) { |
| 13 | + // 调用前初始化 |
| 14 | + if (!this.dictMap) { |
| 15 | + this.initDict() |
| 16 | + } |
| 17 | + |
| 18 | + const targetDict = await this.getDict(code) |
| 19 | + |
| 20 | + return { |
| 21 | + data: () => targetDict, |
| 22 | + enum: () => Object.fromEntries(targetDict.map(({ value, label }) => [value, label])), |
| 23 | + valueMap: () => Object.fromEntries(targetDict.map(({ value, ...data }) => [value, data])), |
| 24 | + labelMap: () => Object.fromEntries(targetDict.map(({ label, ...data }) => [label, data])), |
| 25 | + } |
| 26 | + }, |
| 27 | + async getDict(code: string) { |
| 28 | + const isExist = Reflect.has(this.dictMap, code) |
| 29 | + |
| 30 | + if (isExist) { |
| 31 | + return this.dictMap[code] |
| 32 | + } |
| 33 | + else { |
| 34 | + return await this.getDictByNet(code) |
| 35 | + } |
| 36 | + }, |
| 37 | + |
| 38 | + async getDictByNet(code: string) { |
| 39 | + const { data, isSuccess } = await fetchDictList(code) |
| 40 | + if (isSuccess) { |
| 41 | + Reflect.set(this.dictMap, code, data) |
| 42 | + // 同步至session |
| 43 | + session.set('dict', this.dictMap) |
| 44 | + return data |
| 45 | + } |
| 46 | + else { |
| 47 | + throw new Error(`Failed to get ${code} dictionary from network, check ${code} field or network`) |
| 48 | + } |
| 49 | + }, |
| 50 | + initDict() { |
| 51 | + const dict = session.get('dict') |
| 52 | + if (dict) { |
| 53 | + Object.assign(this.dictMap, dict) |
| 54 | + } |
| 55 | + this.isInitDict = true |
| 56 | + }, |
| 57 | + }, |
| 58 | +}) |
0 commit comments