gQuery/src/index.ts

51 lines
923 B
TypeScript
Raw Normal View History

2021-09-30 16:19:53 +00:00
import { writable, get } from "svelte/store";
const newGCache = () => {
const { subscribe, update, set } = writable({});
async function hydrate(newData) {
update((old) => {
return {
...old,
...newData,
};
});
}
return {
subscribe,
set,
update,
hydrate,
};
};
export const gCache = newGCache();
2021-10-01 21:39:41 +00:00
interface CacheFunctionOptions {
update?: boolean;
}
export async function gQuery(
typename,
{ query, variables },
{ update }: CacheFunctionOptions = {}
) {
2021-09-30 16:19:53 +00:00
const current = get(gCache);
// Extremely Naive cache
// Just checks to see if the data is there, if it is, don't
// Hit the network again
2021-10-01 21:39:41 +00:00
// if update option is present, then we want to update the cache
if (!current?.[typename] || update) {
2021-09-30 16:19:53 +00:00
const newData = await query({
variables,
fetch,
});
await gCache.hydrate(newData);
}
}
2021-10-06 21:41:44 +00:00
export * from "./gFetch";