UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

32 lines (31 loc) 1.66 kB
import { CacheProvider } from "../db/CacheProvider.js"; import { ItemStore } from "../db/ItemStore.js"; import { QueryStore } from "../db/QueryStore.js"; import { setMapItem } from "../util/map.js"; import { getSource } from "../util/source.js"; import { createCacheContext } from "./createCacheContext.js"; import { useStore } from "./useStore.js"; /** * Create a data context * - Allows React elements to call `useItem()` and `useQuery()` to access items/queries in a database provider. * - If the database has a `CacheProvider` in its chain then in-memory data will be used in the returned stores. */ export function createDataContext(provider) { // biome-ignore lint/suspicious/noExplicitAny: The outer function enforces the type. const { CacheContext, useCache } = createCacheContext(); // If this provider is backed by an in-memory cache, pass it to the `ItemStore` and `QueryStore` instances we create. const memory = getSource(CacheProvider, provider)?.memory; return { useItem: (collection, id) => { const cache = useCache(); const key = collection && id && `${collection}/${id}`; return useStore(key ? cache.get(key) || setMapItem(cache, key, new ItemStore(collection, id, provider, memory)) : undefined); }, useQuery: (collection, query) => { const cache = useCache(); const key = collection && query && `${collection}?${JSON.stringify(query)}`; return useStore(key ? cache.get(key) || setMapItem(cache, key, new QueryStore(collection, query, provider, memory)) : undefined); }, DataContext: CacheContext, }; }