Fix globals fetch to handle singleton collection shape
This commit is contained in:
@@ -45,6 +45,15 @@ export async function directusOne<T>(collection: string, q: DirectusQuery = {}):
|
|||||||
return data[0]
|
return data[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function directusSingleton<T>(collection: string, q: DirectusQuery = {}): Promise<T> {
|
||||||
|
const url = new URL(`${DIRECTUS_URL}/items/${collection}`)
|
||||||
|
for (const field of q.fields ?? []) url.searchParams.append('fields[]', field)
|
||||||
|
const res = await fetch(url.toString())
|
||||||
|
if (!res.ok) throw new Error(`Directus error ${res.status} on /items/${collection}`)
|
||||||
|
const { data } = (await res.json()) as DirectusItemResponse<T>
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
export function assetUrl(fileId: string | null | undefined, key?: string): string {
|
export function assetUrl(fileId: string | null | undefined, key?: string): string {
|
||||||
if (!fileId) return ''
|
if (!fileId) return ''
|
||||||
const url = new URL(`${DIRECTUS_URL}/assets/${fileId}`)
|
const url = new URL(`${DIRECTUS_URL}/assets/${fileId}`)
|
||||||
|
|||||||
@@ -1,21 +1,13 @@
|
|||||||
import { queryOptions } from '@tanstack/react-query'
|
import { queryOptions } from '@tanstack/react-query'
|
||||||
import { directusList, directusOne } from './directus'
|
import { directusList, directusOne, directusSingleton } from './directus'
|
||||||
import { GLOBALS_ID } from './env'
|
|
||||||
import type { Category, Globals, Menu, MenuRaw, PageEntity, Vendor, VendorListItem } from './types'
|
import type { Category, Globals, Menu, MenuRaw, PageEntity, Vendor, VendorListItem } from './types'
|
||||||
|
|
||||||
export const globalsQuery = queryOptions({
|
export const globalsQuery = queryOptions({
|
||||||
queryKey: ['globals'],
|
queryKey: ['globals'],
|
||||||
queryFn: async (): Promise<Globals> => {
|
queryFn: () => directusSingleton<Globals>('globals', { fields: ['*'] }),
|
||||||
const item = await directusOne<Globals>('globals', { fields: ['*'] })
|
|
||||||
if (!item) throw new Error('globals not found')
|
|
||||||
return item
|
|
||||||
},
|
|
||||||
staleTime: 5 * 60_000,
|
staleTime: 5 * 60_000,
|
||||||
})
|
})
|
||||||
|
|
||||||
// globals is a singleton; if the ID ever changes, we could filter explicitly.
|
|
||||||
export { GLOBALS_ID }
|
|
||||||
|
|
||||||
export const menusQuery = queryOptions({
|
export const menusQuery = queryOptions({
|
||||||
queryKey: ['menus'],
|
queryKey: ['menus'],
|
||||||
queryFn: async (): Promise<Menu[]> => {
|
queryFn: async (): Promise<Menu[]> => {
|
||||||
|
|||||||
Reference in New Issue
Block a user