├── packages └── solid-cache │ ├── pridepack.json │ ├── src │ ├── index.ts │ ├── cache.ts │ ├── fetch.ts │ ├── cache-instance.ts │ └── core.ts │ ├── tsconfig.json │ ├── LICENSE │ ├── package.json │ ├── .gitignore │ └── README.md ├── pnpm-workspace.yaml ├── examples └── demo │ ├── src │ ├── main.tsx │ └── App.tsx │ ├── vite.config.ts │ ├── index.html │ ├── package.json │ └── tsconfig.json ├── package.json ├── lerna.json ├── .vscode └── settings.json ├── LICENSE ├── .gitignore ├── README.md └── biome.json /packages/solid-cache/pridepack.json: -------------------------------------------------------------------------------- 1 | { 2 | "target": "es2018" 3 | } 4 | -------------------------------------------------------------------------------- /packages/solid-cache/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './core'; 2 | export * from './fetch'; 3 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - packages/**/* 3 | - examples/**/* 4 | - docs 5 | onlyBuiltDependencies: 6 | - '@biomejs/biome' 7 | - esbuild 8 | - nx 9 | -------------------------------------------------------------------------------- /examples/demo/src/main.tsx: -------------------------------------------------------------------------------- 1 | import { render } from 'solid-js/web'; 2 | import App from './App'; 3 | 4 | const app = document.getElementById('app'); 5 | 6 | if (app) { 7 | render(() => , app); 8 | } -------------------------------------------------------------------------------- /examples/demo/vite.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite'; 2 | import solidPlugin from 'vite-plugin-solid' 3 | 4 | export default defineConfig({ 5 | plugins: [ 6 | solidPlugin(), 7 | ], 8 | }); 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "root", 3 | "private": true, 4 | "workspaces": ["packages/*", "examples/*"], 5 | "devDependencies": { 6 | "@biomejs/biome": "^1.9.4", 7 | "lerna": "^8.2.1", 8 | "typescript": "^5.8.2" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /packages/solid-cache/src/cache.ts: -------------------------------------------------------------------------------- 1 | let ID = 0; 2 | 3 | export interface Cache { 4 | id: string; 5 | } 6 | 7 | export function createCache(): Cache { 8 | const id = ID; 9 | ID += 1; 10 | return { 11 | id: `cache-${id}`, 12 | }; 13 | } 14 | -------------------------------------------------------------------------------- /lerna.json: -------------------------------------------------------------------------------- 1 | { 2 | "npmClient": "npm", 3 | "packages": [ 4 | "packages/*", 5 | "examples/*" 6 | ], 7 | "command": { 8 | "version": { 9 | "exact": true 10 | }, 11 | "publish": { 12 | "allowBranch": [ 13 | "main" 14 | ], 15 | "registry": "https://registry.npmjs.org/" 16 | } 17 | }, 18 | "version": "0.3.0" 19 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.defaultFormatter": "biomejs.biome", 3 | "[typescript]": { 4 | "editor.defaultFormatter": "biomejs.biome" 5 | }, 6 | "[typescriptreact]": { 7 | "editor.defaultFormatter": "biomejs.biome" 8 | }, 9 | "[javascript]": { 10 | "editor.defaultFormatter": "biomejs.biome" 11 | }, 12 | "[json]": { 13 | "editor.defaultFormatter": "biomejs.biome" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /examples/demo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Demo 8 | 9 | 10 |
11 | 12 | 13 | -------------------------------------------------------------------------------- /examples/demo/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "demo", 3 | "type": "module", 4 | "private": true, 5 | "publishConfig": { 6 | "access": "restricted" 7 | }, 8 | "devDependencies": { 9 | "typescript": "^5.8.2", 10 | "vite": "^6.2.1", 11 | "vite-plugin-solid": "^2.11.6" 12 | }, 13 | "scripts": { 14 | "dev": "vite", 15 | "build": "vite build", 16 | "preview": "vite preview" 17 | }, 18 | "dependencies": { 19 | "solid-cache": "0.3.0", 20 | "solid-js": "^1.9.5" 21 | }, 22 | "version": "0.3.0" 23 | } 24 | -------------------------------------------------------------------------------- /examples/demo/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "exclude": ["node_modules"], 3 | "compilerOptions": { 4 | "module": "ESNext", 5 | "lib": ["DOM", "ESNext"], 6 | "importHelpers": true, 7 | "declaration": true, 8 | "sourceMap": true, 9 | "rootDir": "./src", 10 | "strict": true, 11 | "isolatedModules": true, 12 | "noUnusedLocals": true, 13 | "noUnusedParameters": true, 14 | "noImplicitReturns": true, 15 | "noFallthroughCasesInSwitch": true, 16 | "moduleResolution": "Bundler", 17 | "jsx": "preserve", 18 | "jsxImportSource": "solid-js", 19 | "esModuleInterop": true, 20 | "target": "ES2017" 21 | } 22 | } -------------------------------------------------------------------------------- /packages/solid-cache/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "exclude": ["node_modules"], 3 | "include": ["src", "types"], 4 | "compilerOptions": { 5 | "module": "ESNext", 6 | "lib": ["ESNext", "DOM"], 7 | "importHelpers": true, 8 | "declaration": true, 9 | "sourceMap": true, 10 | "rootDir": "./src", 11 | "strict": true, 12 | "noUnusedLocals": true, 13 | "noUnusedParameters": true, 14 | "noImplicitReturns": true, 15 | "noFallthroughCasesInSwitch": true, 16 | "moduleResolution": "Bundler", 17 | "jsxImportSource": "solid-js", 18 | "esModuleInterop": true, 19 | "target": "ES2018", 20 | "useDefineForClassFields": false, 21 | "declarationMap": true 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /packages/solid-cache/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License Copyright (c) 2025 Alexis Munsayac 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Alexis Munsayac 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # parcel-bundler cache (https://parceljs.org/) 61 | .cache 62 | 63 | # next.js build output 64 | .next 65 | 66 | # nuxt.js build output 67 | .nuxt 68 | 69 | # vuepress build output 70 | .vuepress/dist 71 | 72 | # Serverless directories 73 | .serverless 74 | 75 | # FuseBox cache 76 | .fusebox/ 77 | -------------------------------------------------------------------------------- /packages/solid-cache/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "solid-cache", 3 | "type": "module", 4 | "version": "0.3.0", 5 | "files": [ 6 | "dist", 7 | "src" 8 | ], 9 | "engines": { 10 | "node": ">=10" 11 | }, 12 | "license": "MIT", 13 | "keywords": [ 14 | "pridepack" 15 | ], 16 | "devDependencies": { 17 | "@types/node": "^22.13.10", 18 | "pridepack": "2.6.4", 19 | "solid-js": "^1.9.5", 20 | "tslib": "^2.8.1", 21 | "typescript": "^5.8.2" 22 | }, 23 | "peerDependencies": { 24 | "solid-js": "^1.3" 25 | }, 26 | "scripts": { 27 | "prepublishOnly": "pridepack clean && pridepack build", 28 | "build": "pridepack build", 29 | "type-check": "pridepack check", 30 | "clean": "pridepack clean" 31 | }, 32 | "description": "Cached data-fetching for SolidJS", 33 | "repository": { 34 | "url": "https://github.com/lxsmnsyc/solid-cache.git", 35 | "type": "git" 36 | }, 37 | "homepage": "https://github.com/lxsmnsyc/solid-cache/tree/main/packages/solid-cache", 38 | "bugs": { 39 | "url": "https://github.com/lxsmnsyc/solid-cache/issues" 40 | }, 41 | "publishConfig": { 42 | "access": "public" 43 | }, 44 | "author": "Alexis Munsayac", 45 | "private": false, 46 | "exports": { 47 | ".": { 48 | "types": "./dist/types/index.d.ts", 49 | "development": { 50 | "require": "./dist/cjs/development/index.cjs", 51 | "import": "./dist/esm/development/index.mjs" 52 | }, 53 | "require": "./dist/cjs/production/index.cjs", 54 | "import": "./dist/esm/production/index.mjs" 55 | } 56 | }, 57 | "typesVersions": { 58 | "*": {} 59 | }, 60 | "types": "./dist/types/index.d.ts", 61 | "main": "./dist/cjs/production/index.cjs", 62 | "module": "./dist/esm/production/index.mjs" 63 | } 64 | -------------------------------------------------------------------------------- /examples/demo/src/App.tsx: -------------------------------------------------------------------------------- 1 | import type { JSX } from 'solid-js/jsx-runtime'; 2 | import { 3 | CacheBoundary, 4 | createCachedResource, 5 | useCacheBoundaryRefresh, 6 | fetch, 7 | } from 'solid-cache'; 8 | import { Suspense } from 'solid-js'; 9 | 10 | function sleep(timeout: number): Promise { 11 | return new Promise(resolve => { 12 | setTimeout(resolve, timeout, true); 13 | }); 14 | } 15 | 16 | function Example() { 17 | const { data, isFetching } = createCachedResource({ 18 | key: 'Example', 19 | async get() { 20 | await sleep(1000); 21 | return `Current time: ${new Date()}`; 22 | }, 23 | }); 24 | 25 | return ( 26 | Loading...}> 27 |

32 | {data()} 33 |

34 |
35 | ); 36 | } 37 | 38 | interface DogImageResponse { 39 | message: string; 40 | } 41 | 42 | function DogImage() { 43 | const { data, isFetching } = fetch( 44 | 'https://dog.ceo/api/breed/shiba/images/random', 45 | ).json(); 46 | 47 | return ( 48 | 49 | 50 | 51 | ); 52 | } 53 | 54 | function RefreshAll() { 55 | const refresh = useCacheBoundaryRefresh(); 56 | 57 | return ( 58 | 61 | ); 62 | } 63 | 64 | function RefreshSWR() { 65 | const refresh = useCacheBoundaryRefresh(); 66 | 67 | return ( 68 | 71 | ); 72 | } 73 | 74 | export default function App(): JSX.Element { 75 | return ( 76 | 77 | 78 | 79 | 80 | 81 | 82 | ); 83 | } 84 | -------------------------------------------------------------------------------- /packages/solid-cache/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.production 74 | .env.development 75 | 76 | # parcel-bundler cache (https://parceljs.org/) 77 | .cache 78 | 79 | # Next.js build output 80 | .next 81 | 82 | # Nuxt.js build / generate output 83 | .nuxt 84 | dist 85 | 86 | # Gatsby files 87 | .cache/ 88 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 89 | # https://nextjs.org/blog/next-9-1#public-directory-support 90 | # public 91 | 92 | # vuepress build output 93 | .vuepress/dist 94 | 95 | # Serverless directories 96 | .serverless/ 97 | 98 | # FuseBox cache 99 | .fusebox/ 100 | 101 | # DynamoDB Local files 102 | .dynamodb/ 103 | 104 | # TernJS port file 105 | .tern-port 106 | 107 | .npmrc 108 | -------------------------------------------------------------------------------- /packages/solid-cache/src/fetch.ts: -------------------------------------------------------------------------------- 1 | import type { CachedResource } from './core'; 2 | import { createCachedResource } from './core'; 3 | 4 | const nativeFetch = globalThis.fetch; 5 | 6 | type Signalify = T | (() => T); 7 | 8 | function isSignal(value: Signalify): value is () => T { 9 | return typeof value === 'function'; 10 | } 11 | 12 | function fromSignal(value: Signalify): T { 13 | if (isSignal(value)) { 14 | return value(); 15 | } 16 | return value; 17 | } 18 | 19 | function serializeInput(input: RequestInfo | URL): string { 20 | if (typeof input === 'string') { 21 | return input; 22 | } 23 | if (input instanceof URL) { 24 | return input.toString(); 25 | } 26 | return input.url; 27 | } 28 | 29 | export class FetchResponse { 30 | private input: Signalify; 31 | 32 | private init?: Signalify; 33 | 34 | constructor( 35 | input: Signalify, 36 | init?: Signalify, 37 | ) { 38 | this.input = input; 39 | this.init = init; 40 | } 41 | 42 | arrayBuffer(): CachedResource { 43 | return createCachedResource({ 44 | source: () => fromSignal(this.input), 45 | key: serializeInput, 46 | get: async localInput => { 47 | const response = await nativeFetch(localInput, fromSignal(this.init)); 48 | return response.arrayBuffer(); 49 | }, 50 | }); 51 | } 52 | 53 | blob(): CachedResource { 54 | return createCachedResource({ 55 | source: () => fromSignal(this.input), 56 | key: serializeInput, 57 | get: async localInput => { 58 | const response = await nativeFetch(localInput, fromSignal(this.init)); 59 | return response.blob(); 60 | }, 61 | }); 62 | } 63 | 64 | formData(): CachedResource { 65 | return createCachedResource({ 66 | source: () => fromSignal(this.input), 67 | key: serializeInput, 68 | get: async localInput => { 69 | const response = await nativeFetch(localInput, fromSignal(this.init)); 70 | return response.formData(); 71 | }, 72 | }); 73 | } 74 | 75 | json(): CachedResource { 76 | return createCachedResource({ 77 | source: () => fromSignal(this.input), 78 | key: serializeInput, 79 | get: async localInput => { 80 | const response = await nativeFetch(localInput, fromSignal(this.init)); 81 | return response.json(); 82 | }, 83 | }); 84 | } 85 | 86 | text(): CachedResource { 87 | return createCachedResource({ 88 | source: () => fromSignal(this.input), 89 | key: serializeInput, 90 | get: async localInput => { 91 | const response = await nativeFetch(localInput, fromSignal(this.init)); 92 | return response.text(); 93 | }, 94 | }); 95 | } 96 | } 97 | 98 | export function fetch( 99 | input: Signalify, 100 | init?: Signalify, 101 | ): FetchResponse { 102 | return new FetchResponse(input, init); 103 | } 104 | -------------------------------------------------------------------------------- /packages/solid-cache/src/cache-instance.ts: -------------------------------------------------------------------------------- 1 | import type { Cache } from './cache'; 2 | 3 | export interface CachePending { 4 | status: 'pending'; 5 | value: Promise; 6 | } 7 | 8 | export interface CacheSuccess { 9 | status: 'success'; 10 | value: T; 11 | } 12 | 13 | export interface CacheFailure { 14 | status: 'failure'; 15 | value: any; 16 | } 17 | 18 | export type CacheResult = CachePending | CacheSuccess | CacheFailure; 19 | 20 | export interface CacheData { 21 | data?: CacheResult; 22 | isFetching: boolean; 23 | } 24 | 25 | export type CacheListener = (result: CacheData) => void; 26 | 27 | export interface CacheRecord { 28 | result: CacheData; 29 | listeners: Set>; 30 | } 31 | 32 | export type CacheActionListener = (swr?: boolean) => void; 33 | 34 | export default class CacheInstance { 35 | private alive = true; 36 | 37 | private listeners = new Set(); 38 | 39 | private store = new Map>>(); 40 | 41 | refresh(swr?: boolean): void { 42 | if (this.alive) { 43 | for (const listener of this.listeners.keys()) { 44 | listener(swr); 45 | } 46 | } 47 | } 48 | 49 | trackRefresh(listener: CacheActionListener): () => void { 50 | if (this.alive) { 51 | this.listeners.add(listener); 52 | } 53 | return () => { 54 | this.listeners.delete(listener); 55 | }; 56 | } 57 | 58 | get(cache: Cache, key: string): CacheData { 59 | return this.getRecord(cache, key, { isFetching: false }).result; 60 | } 61 | 62 | private getRecord( 63 | cache: Cache, 64 | key: string, 65 | result: CacheData, 66 | ): CacheRecord { 67 | let currentCache = this.store.get(cache.id); 68 | if (!currentCache) { 69 | currentCache = new Map(); 70 | this.store.set(cache.id, currentCache); 71 | } 72 | let currentRecord = currentCache.get(key); 73 | if (!currentRecord) { 74 | currentRecord = { 75 | result, 76 | listeners: new Set(), 77 | }; 78 | currentCache.set(key, currentRecord); 79 | } 80 | return currentRecord as CacheRecord; 81 | } 82 | 83 | isFetching(cache: Cache, key: string): boolean { 84 | return this.getRecord(cache, key, { isFetching: false }).result.isFetching; 85 | } 86 | 87 | set(cache: Cache, key: string, result: CacheData): void { 88 | if (this.alive) { 89 | const currentRecord = this.getRecord(cache, key, result); 90 | currentRecord.result = result; 91 | for (const listener of currentRecord.listeners.keys()) { 92 | if (!this.alive) { 93 | return; 94 | } 95 | listener(currentRecord.result); 96 | } 97 | } 98 | } 99 | 100 | subscribe( 101 | cache: Cache, 102 | key: string, 103 | listener: CacheListener, 104 | ): () => void { 105 | if (this.alive) { 106 | const currentRecord = this.getRecord(cache, key, { 107 | isFetching: false, 108 | }); 109 | currentRecord.listeners.add(listener); 110 | 111 | return () => { 112 | currentRecord.listeners.delete(listener); 113 | }; 114 | } 115 | 116 | return () => { 117 | // no-op 118 | }; 119 | } 120 | 121 | destroy(): void { 122 | this.store.clear(); 123 | this.listeners.clear(); 124 | this.alive = false; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # solid-cache 2 | 3 | > Cache boundaries and resource caching in SolidJS 4 | 5 | [![NPM](https://img.shields.io/npm/v/solid-cache.svg)](https://www.npmjs.com/package/solid-cache) [![JavaScript Style Guide](https://badgen.net/badge/code%20style/airbnb/ff5a5f?icon=airbnb)](https://github.com/airbnb/javascript)[![Open in CodeSandbox](https://img.shields.io/badge/Open%20in-CodeSandbox-blue?style=flat-square&logo=codesandbox)](https://codesandbox.io/s/github/LXSMNSYC/solid-cache/tree/main/examples/demo) 6 | 7 | ## Install 8 | 9 | ```bash 10 | npm i solid-cache 11 | ``` 12 | 13 | ```bash 14 | yarn add solid-cache 15 | ``` 16 | 17 | ```bash 18 | pnpm add solid-cache 19 | ``` 20 | 21 | ## Usage 22 | 23 | ### `` 24 | 25 | `` creates a contextual cache for all the cached resources to read/write resource results. 26 | 27 | ```jsx 28 | import { CacheBoundary } from 'solid-cache'; 29 | 30 | export default function App() { 31 | return ( 32 | 33 |
34 | 35 | ); 36 | } 37 | ``` 38 | 39 | It's ideal to add a `` at the root of your application, but you can also do it granularly such that different parts of the application don't have to share the same cache. 40 | 41 | ```jsx 42 | <> 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | ``` 51 | 52 | ### `createCachedResource` 53 | 54 | A primitive similar to `createResource`, except `createCachedResource` works differently. 55 | 56 | For `createCacheResource` to be "cached", it requires a `` as an ancestor component, and it needs a "key" so it knows where to access or share its cached data. 57 | 58 | `createCachedResource` also returns `data` and `isFetching`: `data` is a `Resource` while `isFetching` is a reactive boolean signal. 59 | 60 | ```jsx 61 | import { createCachedResource } from 'solid-cache'; 62 | 63 | function Profile() { 64 | const { data, isFetching } = createCachedResource({ 65 | key: '/profile', 66 | get: () => getUserProfile(), 67 | }); 68 | 69 | return ( 70 |
75 | }> 76 | 77 | 78 | 79 |
80 | ); 81 | } 82 | ``` 83 | 84 | `createCachedResource` can also accept a `source` like `createResource` however it won't refetch if the `key` remains unchanged. 85 | 86 | ```jsx 87 | const { data, isFetching } = createCachedResource({ 88 | source: () => id(), 89 | key: (currentId) => `/user/${currentId}`, 90 | get: (currentID) => getUser(currentId), 91 | }); 92 | ``` 93 | 94 | If there are multiple `createCachedResource` instances that share the same key, only one is going to fetch and the rest will re-use the same cached value as the fetching instance. 95 | 96 | ### `useCacheBoundaryRefresh` 97 | 98 | `useCacheBoundaryRefresh` returns a function that makes all `createCachedResource` instances to simultaneously refresh in the same ``. 99 | 100 | ```js 101 | function RefreshUser() { 102 | const refresh = useCacheBoundaryRefresh(); 103 | 104 | return refresh()} /> 105 | } 106 | ``` 107 | 108 | However, if you want to "refresh in the background" while keeping the old data, you can call `refresh(true)` instead, this way, the UI doesn't need to show a loading UI. 109 | 110 | ### `fetch` 111 | 112 | A wrapper for `createCachedResource` and the native `fetch` API. 113 | 114 | ```jsx 115 | import { fetch } from 'solid-cache'; 116 | 117 | function DogImage() { 118 | const { data, isFetching } = fetch('https://dog.ceo/api/breed/shiba/images/random').json(); 119 | 120 | return ( 121 | 122 | 126 | 127 | ); 128 | } 129 | ``` 130 | 131 | ## Sponsors 132 | 133 | ![Sponsors](https://github.com/lxsmnsyc/sponsors/blob/main/sponsors.svg?raw=true) 134 | 135 | ## License 136 | 137 | MIT © [lxsmnsyc](https://github.com/lxsmnsyc) 138 | -------------------------------------------------------------------------------- /packages/solid-cache/README.md: -------------------------------------------------------------------------------- 1 | # solid-cache 2 | 3 | > Cache boundaries and resource caching in SolidJS 4 | 5 | [![NPM](https://img.shields.io/npm/v/solid-cache.svg)](https://www.npmjs.com/package/solid-cache) [![JavaScript Style Guide](https://badgen.net/badge/code%20style/airbnb/ff5a5f?icon=airbnb)](https://github.com/airbnb/javascript)[![Open in CodeSandbox](https://img.shields.io/badge/Open%20in-CodeSandbox-blue?style=flat-square&logo=codesandbox)](https://codesandbox.io/s/github/LXSMNSYC/solid-cache/tree/main/examples/demo) 6 | 7 | ## Install 8 | 9 | ```bash 10 | npm i solid-cache 11 | ``` 12 | 13 | ```bash 14 | yarn add solid-cache 15 | ``` 16 | 17 | ```bash 18 | pnpm add solid-cache 19 | ``` 20 | 21 | ## Usage 22 | 23 | ### `` 24 | 25 | `` creates a contextual cache for all the cached resources to read/write resource results. 26 | 27 | ```jsx 28 | import { CacheBoundary } from 'solid-cache'; 29 | 30 | export default function App() { 31 | return ( 32 | 33 |
34 | 35 | ); 36 | } 37 | ``` 38 | 39 | It's ideal to add a `` at the root of your application, but you can also do it granularly such that different parts of the application don't have to share the same cache. 40 | 41 | ```jsx 42 | <> 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | ``` 51 | 52 | ### `createCachedResource` 53 | 54 | A primitive similar to `createResource`, except `createCachedResource` works differently. 55 | 56 | For `createCacheResource` to be "cached", it requires a `` as an ancestor component, and it needs a "key" so it knows where to access or share its cached data. 57 | 58 | `createCachedResource` also returns `data` and `isFetching`: `data` is a `Resource` while `isFetching` is a reactive boolean signal. 59 | 60 | ```jsx 61 | import { createCachedResource } from 'solid-cache'; 62 | 63 | function Profile() { 64 | const { data, isFetching } = createCachedResource({ 65 | key: '/profile', 66 | get: () => getUserProfile(), 67 | }); 68 | 69 | return ( 70 |
75 | }> 76 | 77 | 78 | 79 |
80 | ); 81 | } 82 | ``` 83 | 84 | `createCachedResource` can also accept a `source` like `createResource` however it won't refetch if the `key` remains unchanged. 85 | 86 | ```jsx 87 | const { data, isFetching } = createCachedResource({ 88 | source: () => id(), 89 | key: (currentId) => `/user/${currentId}`, 90 | get: (currentID) => getUser(currentId), 91 | }); 92 | ``` 93 | 94 | If there are multiple `createCachedResource` instances that share the same key, only one is going to fetch and the rest will re-use the same cached value as the fetching instance. 95 | 96 | ### `useCacheBoundaryRefresh` 97 | 98 | `useCacheBoundaryRefresh` returns a function that makes all `createCachedResource` instances to simultaneously refresh in the same ``. 99 | 100 | ```js 101 | function RefreshUser() { 102 | const refresh = useCacheBoundaryRefresh(); 103 | 104 | return refresh()} /> 105 | } 106 | ``` 107 | 108 | However, if you want to "refresh in the background" while keeping the old data, you can call `refresh(true)` instead, this way, the UI doesn't need to show a loading UI. 109 | 110 | ### `fetch` 111 | 112 | A wrapper for `createCachedResource` and the native `fetch` API. 113 | 114 | ```jsx 115 | import { fetch } from 'solid-cache'; 116 | 117 | function DogImage() { 118 | const { data, isFetching } = fetch('https://dog.ceo/api/breed/shiba/images/random').json(); 119 | 120 | return ( 121 | 122 | 126 | 127 | ); 128 | } 129 | ``` 130 | 131 | ## Sponsors 132 | 133 | ![Sponsors](https://github.com/lxsmnsyc/sponsors/blob/main/sponsors.svg?raw=true) 134 | 135 | ## License 136 | 137 | MIT © [lxsmnsyc](https://github.com/lxsmnsyc) 138 | -------------------------------------------------------------------------------- /biome.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://unpkg.com/@biomejs/biome/configuration_schema.json", 3 | "files": { 4 | "ignore": ["node_modules/**/*"] 5 | }, 6 | "vcs": { 7 | "useIgnoreFile": true 8 | }, 9 | "linter": { 10 | "enabled": true, 11 | "ignore": ["node_modules/**/*"], 12 | "rules": { 13 | "recommended": true, 14 | "a11y": { 15 | "noAriaHiddenOnFocusable": "off", 16 | "useIframeTitle": "warn", 17 | "useKeyWithClickEvents": "warn", 18 | "useKeyWithMouseEvents": "warn" 19 | }, 20 | "complexity": { 21 | "noForEach": "error", 22 | "noVoid": "off", 23 | "useOptionalChain": "warn", 24 | "useSimplifiedLogicExpression": "error" 25 | }, 26 | "correctness": { 27 | "noConstantMathMinMaxClamp": "error", 28 | "noInvalidNewBuiltin": "error", 29 | "noNewSymbol": "error", 30 | "noNodejsModules": "off", 31 | "noUndeclaredDependencies": "off", 32 | "noUndeclaredVariables": "error", 33 | "noUnusedFunctionParameters": "error", 34 | "noUnusedImports": "error", 35 | "noUnusedPrivateClassMembers": "error", 36 | "noUnusedVariables": "error", 37 | "useArrayLiterals": "error" 38 | }, 39 | "performance": { 40 | "noAccumulatingSpread": "error", 41 | "useTopLevelRegex": "error" 42 | }, 43 | "security": { 44 | "noGlobalEval": "off" 45 | }, 46 | "style": { 47 | "noArguments": "error", 48 | "noImplicitBoolean": "error", 49 | "noInferrableTypes": "error", 50 | "noNamespace": "error", 51 | "noNegationElse": "error", 52 | "noRestrictedGlobals": "error", 53 | "noShoutyConstants": "error", 54 | "noUnusedTemplateLiteral": "error", 55 | "noUselessElse": "error", 56 | "noVar": "error", 57 | "noYodaExpression": "error", 58 | "useAsConstAssertion": "error", 59 | "useBlockStatements": "error", 60 | "useCollapsedElseIf": "error", 61 | "useConsistentArrayType": "error", 62 | "useConsistentBuiltinInstantiation": "error", 63 | "useConst": "error", 64 | "useDefaultParameterLast": "error", 65 | "useEnumInitializers": "error", 66 | "useExponentiationOperator": "error", 67 | "useExportType": "error", 68 | "useFragmentSyntax": "error", 69 | "useForOf": "warn", 70 | "useImportType": "error", 71 | "useLiteralEnumMembers": "error", 72 | "useNodejsImportProtocol": "warn", 73 | "useNumberNamespace": "error", 74 | "useNumericLiterals": "error", 75 | "useSelfClosingElements": "error", 76 | "useShorthandArrayType": "error", 77 | "useShorthandAssign": "error", 78 | "useShorthandFunctionType": "warn", 79 | "useSingleCaseStatement": "error", 80 | "useSingleVarDeclarator": "error", 81 | "useTemplate": "off", 82 | "useWhile": "error" 83 | }, 84 | "suspicious": { 85 | "noConsoleLog": "warn", 86 | "noConstEnum": "off", 87 | "noDebugger": "off", 88 | "noEmptyBlockStatements": "error", 89 | "noExplicitAny": "warn", 90 | "noImplicitAnyLet": "off", 91 | "noMisrefactoredShorthandAssign": "off", 92 | "noSelfCompare": "off", 93 | "noSparseArray": "off", 94 | "noThenProperty": "warn", 95 | "useAwait": "error", 96 | "useErrorMessage": "error" 97 | } 98 | } 99 | }, 100 | "formatter": { 101 | "enabled": true, 102 | "ignore": ["node_modules/**/*"], 103 | "formatWithErrors": false, 104 | "indentWidth": 2, 105 | "indentStyle": "space", 106 | "lineEnding": "lf", 107 | "lineWidth": 80 108 | }, 109 | "organizeImports": { 110 | "enabled": true, 111 | "ignore": ["node_modules/**/*"] 112 | }, 113 | "javascript": { 114 | "formatter": { 115 | "enabled": true, 116 | "arrowParentheses": "asNeeded", 117 | "bracketSameLine": false, 118 | "bracketSpacing": true, 119 | "indentWidth": 2, 120 | "indentStyle": "space", 121 | "jsxQuoteStyle": "double", 122 | "lineEnding": "lf", 123 | "lineWidth": 80, 124 | "quoteProperties": "asNeeded", 125 | "quoteStyle": "single", 126 | "semicolons": "always", 127 | "trailingCommas": "all" 128 | }, 129 | "globals": [], 130 | "parser": { 131 | "unsafeParameterDecoratorsEnabled": true 132 | } 133 | }, 134 | "json": { 135 | "formatter": { 136 | "enabled": true, 137 | "indentWidth": 2, 138 | "indentStyle": "space", 139 | "lineEnding": "lf", 140 | "lineWidth": 80 141 | }, 142 | "parser": { 143 | "allowComments": false, 144 | "allowTrailingCommas": false 145 | } 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /packages/solid-cache/src/core.ts: -------------------------------------------------------------------------------- 1 | /* @jsxImportSource solid-js */ 2 | import type { JSX, Resource } from 'solid-js'; 3 | import { 4 | createComponent, 5 | createContext, 6 | createMemo, 7 | createRenderEffect, 8 | createResource, 9 | createSignal, 10 | on, 11 | onCleanup, 12 | untrack, 13 | useContext, 14 | } from 'solid-js'; 15 | import { createCache } from './cache'; 16 | import type { CacheData, CacheResult } from './cache-instance'; 17 | import CacheInstance from './cache-instance'; 18 | 19 | function signalToResource( 20 | result: () => CacheResult | undefined, 21 | ): Resource { 22 | const [data] = createResource( 23 | () => result(), 24 | async currentResult => { 25 | if (currentResult.status === 'failure') { 26 | throw currentResult.value; 27 | } 28 | return await currentResult.value; 29 | }, 30 | ); 31 | 32 | return data; 33 | } 34 | 35 | const CacheContext = createContext(); 36 | 37 | export interface CacheBoundaryProps { 38 | children?: JSX.Element; 39 | } 40 | 41 | export function CacheBoundary(props: CacheBoundaryProps): JSX.Element { 42 | const instance = new CacheInstance(); 43 | 44 | onCleanup(() => { 45 | instance.destroy(); 46 | }); 47 | 48 | return createComponent(CacheContext.Provider, { 49 | value: instance, 50 | get children() { 51 | return props.children; 52 | }, 53 | }); 54 | } 55 | 56 | function useCacheContext(): CacheInstance { 57 | const ctx = useContext(CacheContext); 58 | 59 | if (!ctx) { 60 | throw new Error('Missing ``'); 61 | } 62 | 63 | return ctx; 64 | } 65 | 66 | export function useCacheBoundaryRefresh(): (swr?: boolean) => void { 67 | const ctx = useCacheContext(); 68 | 69 | return (swr?: boolean) => { 70 | ctx.refresh(swr); 71 | }; 72 | } 73 | 74 | const cachedResource = createCache(); 75 | 76 | export interface CachedResource { 77 | data: Resource; 78 | isFetching: () => boolean; 79 | } 80 | 81 | export interface CachedResourceOptionsWithSource { 82 | source: () => Source; 83 | key: (currentSource: Source) => string; 84 | get: (currentSource: Source) => Promise; 85 | } 86 | 87 | export interface CachedResourceOptionsWithoutSource { 88 | key: string; 89 | get: () => Promise; 90 | } 91 | 92 | function createCachedResourceWithSource( 93 | options: CachedResourceOptionsWithSource, 94 | ): CachedResource { 95 | const ctx = useCacheContext(); 96 | 97 | const currentSource = createMemo(() => options.source()); 98 | const currentKey = createMemo(() => options.key(currentSource())); 99 | 100 | const [result, setResult] = createSignal>( 101 | ctx.get(cachedResource, untrack(currentKey)), 102 | ); 103 | 104 | // Bind cache to local signal 105 | createRenderEffect(() => { 106 | const targetKey = currentKey(); 107 | 108 | onCleanup(ctx.subscribe(cachedResource, targetKey, setResult)); 109 | 110 | // Sync local signal 111 | setResult(ctx.get(cachedResource, targetKey)); 112 | }); 113 | 114 | function createRecord( 115 | targetKey: string, 116 | targetSource: Source, 117 | swr?: boolean, 118 | ): void { 119 | // Dedupe when there's an on-going fetch 120 | if (ctx.isFetching(cachedResource, targetKey)) { 121 | return; 122 | } 123 | 124 | const fetchedResult = options.get(targetSource); 125 | 126 | fetchedResult.then( 127 | value => { 128 | ctx.set(cachedResource, targetKey, { 129 | data: { 130 | status: 'success', 131 | value, 132 | }, 133 | isFetching: false, 134 | }); 135 | }, 136 | value => { 137 | ctx.set(cachedResource, targetKey, { 138 | data: { 139 | status: 'failure', 140 | value, 141 | }, 142 | isFetching: false, 143 | }); 144 | }, 145 | ); 146 | 147 | if (swr) { 148 | ctx.set(cachedResource, targetKey, { 149 | data: ctx.get(cachedResource, targetKey)?.data, 150 | isFetching: true, 151 | }); 152 | } else { 153 | ctx.set(cachedResource, targetKey, { 154 | data: { 155 | status: 'pending', 156 | value: fetchedResult, 157 | }, 158 | isFetching: true, 159 | }); 160 | } 161 | } 162 | 163 | // Manage fetcher 164 | createRenderEffect( 165 | on(currentKey, keyValue => { 166 | const currentResult = ctx.get(cachedResource, keyValue); 167 | if (!currentResult.data) { 168 | createRecord(keyValue, untrack(currentSource), false); 169 | } 170 | }), 171 | ); 172 | 173 | // Manage fetcher by refresh action 174 | createRenderEffect(() => { 175 | onCleanup( 176 | ctx.trackRefresh(swr => { 177 | createRecord(untrack(currentKey), untrack(currentSource), swr); 178 | }), 179 | ); 180 | }); 181 | 182 | return { 183 | data: signalToResource(() => result().data), 184 | isFetching: () => result().isFetching, 185 | }; 186 | } 187 | 188 | function createCachedResourceWithoutSource( 189 | options: CachedResourceOptionsWithoutSource, 190 | ): CachedResource { 191 | const ctx = useCacheContext(); 192 | 193 | const key = untrack(() => options.key); 194 | 195 | const [result, setResult] = createSignal>( 196 | ctx.get(cachedResource, key), 197 | ); 198 | 199 | // Bind cache to local signal 200 | createRenderEffect(() => { 201 | onCleanup(ctx.subscribe(cachedResource, key, setResult)); 202 | 203 | // Sync local signal 204 | setResult(ctx.get(cachedResource, key)); 205 | }); 206 | 207 | function createRecord(targetKey: string, swr?: boolean): void { 208 | // Dedupe when there's an on-going fetch 209 | if (ctx.isFetching(cachedResource, targetKey)) { 210 | return; 211 | } 212 | 213 | const fetchedResult = options.get(); 214 | 215 | fetchedResult.then( 216 | value => { 217 | ctx.set(cachedResource, targetKey, { 218 | data: { 219 | status: 'success', 220 | value, 221 | }, 222 | isFetching: false, 223 | }); 224 | }, 225 | value => { 226 | ctx.set(cachedResource, targetKey, { 227 | data: { 228 | status: 'failure', 229 | value, 230 | }, 231 | isFetching: false, 232 | }); 233 | }, 234 | ); 235 | 236 | if (swr) { 237 | ctx.set(cachedResource, targetKey, { 238 | data: ctx.get(cachedResource, targetKey)?.data, 239 | isFetching: true, 240 | }); 241 | } else { 242 | ctx.set(cachedResource, targetKey, { 243 | data: { 244 | status: 'pending', 245 | value: fetchedResult, 246 | }, 247 | isFetching: true, 248 | }); 249 | } 250 | } 251 | 252 | const currentResult = ctx.get(cachedResource, key); 253 | if (!currentResult.data) { 254 | createRecord(key, false); 255 | } 256 | 257 | // Manage fetcher by refresh action 258 | createRenderEffect(() => { 259 | onCleanup( 260 | ctx.trackRefresh(swr => { 261 | createRecord(key, swr); 262 | }), 263 | ); 264 | }); 265 | 266 | return { 267 | data: signalToResource(() => result().data), 268 | isFetching: () => result().isFetching, 269 | }; 270 | } 271 | 272 | export function createCachedResource( 273 | options: CachedResourceOptionsWithSource, 274 | ): CachedResource; 275 | export function createCachedResource( 276 | options: CachedResourceOptionsWithoutSource, 277 | ): CachedResource; 278 | export function createCachedResource( 279 | options: 280 | | CachedResourceOptionsWithSource 281 | | CachedResourceOptionsWithoutSource, 282 | ): CachedResource { 283 | if ('source' in options) { 284 | return createCachedResourceWithSource(options); 285 | } 286 | return createCachedResourceWithoutSource(options); 287 | } 288 | --------------------------------------------------------------------------------