|
1 | | -export { useField, FieldType } from '@storipress/custom-field' |
| 1 | +import type { UseFieldOptions, UseFieldReturn } from '@storipress/custom-field' |
| 2 | +import { FieldType, useField as _useField, normalizeOptions } from '@storipress/custom-field' |
| 3 | +import type { ResourceID } from '../types' |
| 4 | +import { useResourceResolver } from './resources' |
| 5 | + |
| 6 | +interface ReferenceValue { |
| 7 | + articleId?: string |
| 8 | + deskId?: string |
| 9 | + tagId?: string |
| 10 | + userId?: string |
| 11 | +} |
| 12 | + |
| 13 | +function getReferenceResourceID({ articleId, deskId, tagId, userId }: ReferenceValue = {}): ResourceID { |
| 14 | + if (articleId) return { type: 'article', id: articleId } |
| 15 | + if (deskId) return { type: 'desk', id: deskId } |
| 16 | + if (tagId) return { type: 'tag', id: tagId } |
| 17 | + if (userId) return { type: 'author', id: userId } |
| 18 | + |
| 19 | + return null as never |
| 20 | +} |
| 21 | + |
| 22 | +export function useField(key: string): UseFieldReturn<undefined, false> |
| 23 | +export function useField<Type extends FieldType>(key: string, type: Type): UseFieldReturn<Type, false> |
| 24 | +export function useField<Type extends FieldType, IsAll extends boolean>( |
| 25 | + key: string, |
| 26 | + type: Type, |
| 27 | + all: IsAll, |
| 28 | +): UseFieldReturn<Type, IsAll> |
| 29 | +export function useField<Type extends FieldType, IsAll extends boolean>( |
| 30 | + key: string, |
| 31 | + options: UseFieldOptions<Type, IsAll>, |
| 32 | + _all?: IsAll, |
| 33 | +): UseFieldReturn<Type, IsAll> |
| 34 | +export function useField( |
| 35 | + key: string, |
| 36 | + type_?: FieldType | UseFieldOptions<FieldType, boolean>, |
| 37 | + all_ = false, |
| 38 | +): Ref<unknown> { |
| 39 | + const { type } = normalizeOptions(type_, all_) |
| 40 | + |
| 41 | + const field = _useField(key, type_ as FieldType, all_) |
| 42 | + if (!field.value) return field |
| 43 | + |
| 44 | + if (type === FieldType.Ref) { |
| 45 | + const { resolveFromID } = useResourceResolver() |
| 46 | + |
| 47 | + const { data } = useAsyncData( |
| 48 | + `resource-meta-${key}::${type}`, |
| 49 | + async () => { |
| 50 | + const refValue = field.value as ReferenceValue[] |
| 51 | + const promises = refValue.map((value) => { |
| 52 | + const resourceID = getReferenceResourceID(value) |
| 53 | + return resolveFromID(resourceID) |
| 54 | + }) |
| 55 | + return await Promise.all(promises) |
| 56 | + }, |
| 57 | + { |
| 58 | + watch: [field], |
| 59 | + }, |
| 60 | + ) |
| 61 | + |
| 62 | + return computed(() => { |
| 63 | + return data.value?.map((resource) => resource?.meta) |
| 64 | + }) |
| 65 | + } |
| 66 | + |
| 67 | + return field |
| 68 | +} |
| 69 | + |
| 70 | +export { FieldType } |
0 commit comments