Skip to content

Commit

Permalink
added invocation tracking to cache records
Browse files Browse the repository at this point in the history
  • Loading branch information
C-Sinclair committed Feb 20, 2024
1 parent a09c634 commit 49f38dc
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/query.svelte.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ export type CacheObject = {
* A function that will fetch the data and update the cache record
*/
fetcher: () => void;
/**
* A list of invocation times for the fetcher
*/
invocations: [number, number][];
};
};

Expand Down
8 changes: 8 additions & 0 deletions src/query.svelte.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,24 @@ export function createQuery(fn, config = {}) {

// the fetcher uses closures to re-run the same query with the same args when needed
function fetcher() {
let start = Date.now();
cache[key].loading = true;
cache[key].error = undefined;
fn(...args)
.then((result) => {
let end = Date.now();

// this is reactive, so mutating the data will be picked up by Svelte
cache[key].data = result;
cache[key].loading = false;
cache[key].invocations.push([start, end]);
})
.catch((error) => {
let end = Date.now();

cache[key].error = error;
cache[key].loading = false;
cache[key].invocations.push([start, end]);

if (invalidateDataOnError) {
cache[key].data = undefined;
Expand All @@ -67,6 +74,7 @@ export function createQuery(fn, config = {}) {
error: undefined,
loading: true,
fetcher,
invocations: [],
};

// immediately trigger the fetcher
Expand Down

0 comments on commit 49f38dc

Please sign in to comment.