{"id":24397734,"url":"https://github.com/thalesfp/query-with-cache","last_synced_at":"2026-06-17T20:01:23.356Z","repository":{"id":272851534,"uuid":"905380903","full_name":"thalesfp/query-with-cache","owner":"thalesfp","description":"Lightweight caching solution for async queries","archived":false,"fork":false,"pushed_at":"2025-01-17T01:47:32.000Z","size":97,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-13T05:25:48.078Z","etag":null,"topics":["cache","query","valtio"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/thalesfp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-12-18T17:52:51.000Z","updated_at":"2025-01-17T01:47:33.000Z","dependencies_parsed_at":"2025-01-17T02:30:54.315Z","dependency_job_id":null,"html_url":"https://github.com/thalesfp/query-with-cache","commit_stats":null,"previous_names":["thalesfp/query-with-cache"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/thalesfp/query-with-cache","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thalesfp%2Fquery-with-cache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thalesfp%2Fquery-with-cache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thalesfp%2Fquery-with-cache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thalesfp%2Fquery-with-cache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/thalesfp","download_url":"https://codeload.github.com/thalesfp/query-with-cache/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/thalesfp%2Fquery-with-cache/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34463558,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-17T02:00:05.408Z","response_time":127,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cache","query","valtio"],"created_at":"2025-01-19T22:39:26.735Z","updated_at":"2026-06-17T20:01:23.340Z","avatar_url":"https://github.com/thalesfp.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# query-with-cache\n\nA lightweight, TypeScript-first caching solution for managing async query results. Inspired by React Query's patterns, it provides a simple yet powerful way to cache and invalidate data with support for stale-while-revalidate, automatic garbage collection, and hierarchical cache keys.\n\n## Features\n\n- 🚀 Simple, intuitive API\n- 💾 In-memory caching with automatic garbage collection\n- 🌳 Hierarchical cache keys\n- ⚡ Stale-while-revalidate pattern\n- 🔍 TypeScript-first design\n- 🧹 Zero dependencies\n\n## Installation\n\n```bash\nnpm install query-with-cache\n# or\nyarn add query-with-cache\n```\n\n## Quick Start\n\n```typescript\nimport { queryWithCache, CacheStoreInMemory } from 'query-with-cache';\n\n// Create a cache instance\nconst cache = new CacheStoreInMemory();\n\n// Basic usage\nawait queryWithCache({\n  queryKey: ['todos'],\n  cache,\n  queryFn: () =\u003e fetch('/api/todos').then(r =\u003e r.json()),\n  onData: (todos) =\u003e {\n    console.log('Todos:', todos);\n  },\n  onIsFetching: (loading) =\u003e {\n    console.log('Loading:', loading);\n  },\n  onError: (error) =\u003e {\n    console.error('Error:', error);\n  },\n});\n```\n\n## Integration with Valtio\n\n```typescript\nimport { proxy } from 'valtio';\n\n// Define your state\ninterface State {\n  todos: Todo[];\n  isLoading: boolean;\n  error: Error | null;\n}\n\nconst state = proxy\u003cState\u003e({\n  todos: [],\n  isLoading: false,\n  error: null,\n});\n\n// Create data fetching function\nconst fetchTodos = async () =\u003e {\n  await queryWithCache({\n    queryKey: ['todos'],\n    cache,\n    queryFn: () =\u003e fetch('/api/todos').then(r =\u003e r.json()),\n    onData: (todos) =\u003e {\n      state.todos = todos;\n    },\n    onIsFetching: (loading) =\u003e {\n      state.isLoading = loading;\n    },\n    onError: (error) =\u003e {\n      state.error = error as Error;\n    },\n  });\n};\n\n// Use with React\nimport { useSnapshot } from 'valtio';\n\nfunction TodoList() {\n  const snap = useSnapshot(state);\n\n  useEffect(() =\u003e {\n    fetchTodos();\n  }, []);\n\n  if (snap.isLoading) return \u003cdiv\u003eLoading...\u003c/div\u003e;\n  if (snap.error) return \u003cdiv\u003eError: {snap.error.message}\u003c/div\u003e;\n\n  return (\n    \u003cul\u003e\n      {snap.todos.map(todo =\u003e (\n        \u003cli key={todo.id}\u003e{todo.title}\u003c/li\u003e\n      ))}\n    \u003c/ul\u003e\n  );\n}\n```\n\n### Optimistic Updates with Valtio\n\n```typescript\nconst addTodo = async (newTodo: Todo) =\u003e {\n  // Optimistic update\n  state.todos.push({ ...newTodo, id: 'temp-id' });\n\n  try {\n    await queryWithCache({\n      queryKey: ['todos', 'add'],\n      cache,\n      queryFn: () =\u003e fetch('/api/todos', {\n        method: 'POST',\n        body: JSON.stringify(newTodo),\n      }).then(r =\u003e r.json()),\n      onData: (savedTodo) =\u003e {\n        // Replace optimistic todo with server response\n        const index = state.todos.findIndex(t =\u003e t.id === 'temp-id');\n        if (index !== -1) {\n          state.todos[index] = savedTodo;\n        }\n      },\n      onError: () =\u003e {\n        // Rollback on error\n        state.todos = state.todos.filter(t =\u003e t.id !== 'temp-id');\n      },\n    });\n  } catch (error) {\n    // Handle error\n    state.todos = state.todos.filter(t =\u003e t.id !== 'temp-id');\n  }\n};\n```\n\n## Basic Cache Operations\n\n```typescript\n// Set cache entry\ncache.set({\n  key: ['users', '123'],\n  data: userData,\n  staleTime: 5000,    // Optional: custom stale time\n  cacheTime: 30000,   // Optional: custom cache time\n});\n\n// Get cache entry\nconst { data, stale } = cache.get(['users', '123']);\n\n// Invalidate cache entries\ncache.invalidate(['users', '123']);     // Single entry\ncache.invalidate(['users']);            // Collection\n```\n\n## TypeScript Support\n\n```typescript\ninterface Todo {\n  id: string;\n  title: string;\n  completed: boolean;\n}\n\n// Typed cache operations\nconst { data, stale } = cache.get\u003cTodo\u003e(['todos', '123']);\n\n// Typed queries\nawait queryWithCache\u003cTodo[]\u003e({\n  queryKey: ['todos'],\n  queryFn: () =\u003e fetchTodos(),\n  onData: (todos) =\u003e {\n    // todos is typed as Todo[]\n    console.log(todos[0].title);\n  }\n});\n```\n\n## Configuration\n\n```typescript\nconst cache = new CacheStoreInMemory({\n  // Default times\n  defaultStaleTime: 5000,    // 5 seconds\n  defaultCacheTime: 30000,   // 30 seconds\n  \n  // Garbage collection interval\n  gcInterval: 60000,         // 1 minute\n  \n  // Debugging\n  debug: true,\n  logger: customLogger,\n});\n```\n\n## Best Practices\n\n1. **Cache Keys**\n   ```typescript\n   // Good\n   ['users', userId, 'posts']\n   ['todos', { status: 'active' }]\n\n   // Avoid\n   ['users', new Date()]  // Non-serializable\n   ['data']              // Too generic\n   ```\n\n2. **Cache Times**\n   - Set appropriate stale times based on data freshness needs\n   - Configure cache times based on memory constraints\n   - Use shorter times for frequently changing data\n\n3. **Error Handling**\n   - Always provide error handlers\n   - Implement retry strategies if needed\n   - Handle cache misses appropriately\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthalesfp%2Fquery-with-cache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fthalesfp%2Fquery-with-cache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fthalesfp%2Fquery-with-cache/lists"}