fix(package): Update dependency scopes/versions, fix imports and scripts, add pnpm workspace, remove GitLab CI
This commit is contained in:
139
.gitlab-ci.yml
139
.gitlab-ci.yml
@@ -1,139 +0,0 @@
|
|||||||
# gitzone ci_default
|
|
||||||
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
|
|
||||||
|
|
||||||
cache:
|
|
||||||
paths:
|
|
||||||
- .npmci_cache/
|
|
||||||
key: '$CI_BUILD_STAGE'
|
|
||||||
|
|
||||||
stages:
|
|
||||||
- security
|
|
||||||
- test
|
|
||||||
- release
|
|
||||||
- metadata
|
|
||||||
|
|
||||||
before_script:
|
|
||||||
- npm install -g @shipzone/npmci
|
|
||||||
|
|
||||||
# ====================
|
|
||||||
# security stage
|
|
||||||
# ====================
|
|
||||||
mirror:
|
|
||||||
stage: security
|
|
||||||
script:
|
|
||||||
- npmci git mirror
|
|
||||||
only:
|
|
||||||
- tags
|
|
||||||
tags:
|
|
||||||
- lossless
|
|
||||||
- docker
|
|
||||||
- notpriv
|
|
||||||
|
|
||||||
auditProductionDependencies:
|
|
||||||
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
|
|
||||||
stage: security
|
|
||||||
script:
|
|
||||||
- npmci npm prepare
|
|
||||||
- npmci command npm install --production --ignore-scripts
|
|
||||||
- npmci command npm config set registry https://registry.npmjs.org
|
|
||||||
- npmci command npm audit --audit-level=high --only=prod --production
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
allow_failure: true
|
|
||||||
|
|
||||||
auditDevDependencies:
|
|
||||||
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
|
|
||||||
stage: security
|
|
||||||
script:
|
|
||||||
- npmci npm prepare
|
|
||||||
- npmci command npm install --ignore-scripts
|
|
||||||
- npmci command npm config set registry https://registry.npmjs.org
|
|
||||||
- npmci command npm audit --audit-level=high --only=dev
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
allow_failure: true
|
|
||||||
|
|
||||||
# ====================
|
|
||||||
# test stage
|
|
||||||
# ====================
|
|
||||||
|
|
||||||
testStable:
|
|
||||||
stage: test
|
|
||||||
script:
|
|
||||||
- npmci npm prepare
|
|
||||||
- npmci node install stable
|
|
||||||
- npmci npm install
|
|
||||||
- npmci npm test
|
|
||||||
coverage: /\d+.?\d+?\%\s*coverage/
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
|
|
||||||
testBuild:
|
|
||||||
stage: test
|
|
||||||
script:
|
|
||||||
- npmci npm prepare
|
|
||||||
- npmci node install stable
|
|
||||||
- npmci npm install
|
|
||||||
- npmci command npm run build
|
|
||||||
coverage: /\d+.?\d+?\%\s*coverage/
|
|
||||||
tags:
|
|
||||||
- docker
|
|
||||||
|
|
||||||
release:
|
|
||||||
stage: release
|
|
||||||
script:
|
|
||||||
- npmci node install stable
|
|
||||||
- npmci npm publish
|
|
||||||
only:
|
|
||||||
- tags
|
|
||||||
tags:
|
|
||||||
- lossless
|
|
||||||
- docker
|
|
||||||
- notpriv
|
|
||||||
|
|
||||||
# ====================
|
|
||||||
# metadata stage
|
|
||||||
# ====================
|
|
||||||
codequality:
|
|
||||||
stage: metadata
|
|
||||||
allow_failure: true
|
|
||||||
only:
|
|
||||||
- tags
|
|
||||||
script:
|
|
||||||
- npmci command npm install -g typescript
|
|
||||||
- npmci npm prepare
|
|
||||||
- npmci npm install
|
|
||||||
tags:
|
|
||||||
- lossless
|
|
||||||
- docker
|
|
||||||
- priv
|
|
||||||
|
|
||||||
trigger:
|
|
||||||
stage: metadata
|
|
||||||
script:
|
|
||||||
- npmci trigger
|
|
||||||
only:
|
|
||||||
- tags
|
|
||||||
tags:
|
|
||||||
- lossless
|
|
||||||
- docker
|
|
||||||
- notpriv
|
|
||||||
|
|
||||||
pages:
|
|
||||||
stage: metadata
|
|
||||||
script:
|
|
||||||
- npmci node install stable
|
|
||||||
- npmci npm prepare
|
|
||||||
- npmci npm install
|
|
||||||
- npmci command npm run buildDocs
|
|
||||||
tags:
|
|
||||||
- lossless
|
|
||||||
- docker
|
|
||||||
- notpriv
|
|
||||||
only:
|
|
||||||
- tags
|
|
||||||
artifacts:
|
|
||||||
expire_in: 1 week
|
|
||||||
paths:
|
|
||||||
- public
|
|
||||||
allow_failure: true
|
|
68
.serena/project.yml
Normal file
68
.serena/project.yml
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
# language of the project (csharp, python, rust, java, typescript, go, cpp, or ruby)
|
||||||
|
# * For C, use cpp
|
||||||
|
# * For JavaScript, use typescript
|
||||||
|
# Special requirements:
|
||||||
|
# * csharp: Requires the presence of a .sln file in the project folder.
|
||||||
|
language: typescript
|
||||||
|
|
||||||
|
# whether to use the project's gitignore file to ignore files
|
||||||
|
# Added on 2025-04-07
|
||||||
|
ignore_all_files_in_gitignore: true
|
||||||
|
# list of additional paths to ignore
|
||||||
|
# same syntax as gitignore, so you can use * and **
|
||||||
|
# Was previously called `ignored_dirs`, please update your config if you are using that.
|
||||||
|
# Added (renamed) on 2025-04-07
|
||||||
|
ignored_paths: []
|
||||||
|
|
||||||
|
# whether the project is in read-only mode
|
||||||
|
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
|
||||||
|
# Added on 2025-04-18
|
||||||
|
read_only: false
|
||||||
|
|
||||||
|
|
||||||
|
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
|
||||||
|
# Below is the complete list of tools for convenience.
|
||||||
|
# To make sure you have the latest list of tools, and to view their descriptions,
|
||||||
|
# execute `uv run scripts/print_tool_overview.py`.
|
||||||
|
#
|
||||||
|
# * `activate_project`: Activates a project by name.
|
||||||
|
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
|
||||||
|
# * `create_text_file`: Creates/overwrites a file in the project directory.
|
||||||
|
# * `delete_lines`: Deletes a range of lines within a file.
|
||||||
|
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
|
||||||
|
# * `execute_shell_command`: Executes a shell command.
|
||||||
|
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
|
||||||
|
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
|
||||||
|
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
|
||||||
|
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
||||||
|
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
|
||||||
|
# * `initial_instructions`: Gets the initial instructions for the current project.
|
||||||
|
# Should only be used in settings where the system prompt cannot be set,
|
||||||
|
# e.g. in clients you have no control over, like Claude Desktop.
|
||||||
|
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
|
||||||
|
# * `insert_at_line`: Inserts content at a given line in a file.
|
||||||
|
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
|
||||||
|
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
|
||||||
|
# * `list_memories`: Lists memories in Serena's project-specific memory store.
|
||||||
|
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
|
||||||
|
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
|
||||||
|
# * `read_file`: Reads a file within the project directory.
|
||||||
|
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
|
||||||
|
# * `remove_project`: Removes a project from the Serena configuration.
|
||||||
|
# * `replace_lines`: Replaces a range of lines within a file with new content.
|
||||||
|
# * `replace_symbol_body`: Replaces the full definition of a symbol.
|
||||||
|
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
|
||||||
|
# * `search_for_pattern`: Performs a search for a pattern in the project.
|
||||||
|
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
|
||||||
|
# * `switch_modes`: Activates modes by providing a list of their names
|
||||||
|
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
|
||||||
|
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
|
||||||
|
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
|
||||||
|
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
|
||||||
|
excluded_tools: []
|
||||||
|
|
||||||
|
# initial prompt for the project. It will always be given to the LLM upon activating the project
|
||||||
|
# (contrary to the memories, which are loaded on demand).
|
||||||
|
initial_prompt: ""
|
||||||
|
|
||||||
|
project_name: "smartcache"
|
94
changelog.md
Normal file
94
changelog.md
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
## 2025-08-26 - 1.0.17 - fix(package)
|
||||||
|
Update dependency scopes/versions, fix imports and scripts, add pnpm workspace, remove GitLab CI
|
||||||
|
|
||||||
|
- Normalized package scopes to include dot notation (e.g. @push.rocks/*) and updated internal import paths in TypeScript files
|
||||||
|
- Updated runtime dependencies: @push.rocks/smartdelay -> ^3.0.5, @push.rocks/smartpromise -> ^4.2.3 (other @push.rocks/* deps kept/validated)
|
||||||
|
- Switched dev tooling packages to @git.zone/* namespace and bumped @git.zone/tstest version
|
||||||
|
- Adjusted npm scripts: more verbose test command and changed build target to use tsfolders
|
||||||
|
- Added pnpm-workspace.yaml and packageManager entry in package.json
|
||||||
|
- Removed .gitlab-ci.yml CI configuration
|
||||||
|
|
||||||
|
## 2024-05-29 - 1.0.16 - chore
|
||||||
|
Project metadata and TypeScript configuration updates.
|
||||||
|
|
||||||
|
- Update package description.
|
||||||
|
- Update tsconfig for TypeScript configuration.
|
||||||
|
- Update npmextra.json (githost) entries.
|
||||||
|
- Switch to new organization scheme (org restructuring).
|
||||||
|
|
||||||
|
## 2023-01-08 - 1.0.15 - fix(core)
|
||||||
|
Core fixes and maintenance.
|
||||||
|
|
||||||
|
- Apply core updates and fixes.
|
||||||
|
|
||||||
|
## 2022-06-26 - 1.0.14 - fix(core)
|
||||||
|
Core fixes and maintenance.
|
||||||
|
|
||||||
|
- Apply core updates and fixes.
|
||||||
|
|
||||||
|
## 2021-04-21 - 1.0.13 - fix(core)
|
||||||
|
Core fixes and maintenance.
|
||||||
|
|
||||||
|
- Apply core updates and fixes.
|
||||||
|
|
||||||
|
## 2020-02-03 - 1.0.12 - fix(core)
|
||||||
|
Core fixes and maintenance.
|
||||||
|
|
||||||
|
- Apply core updates and fixes.
|
||||||
|
|
||||||
|
## 2019-10-23 - 1.0.11 - fix(core)
|
||||||
|
Core fixes and maintenance.
|
||||||
|
|
||||||
|
- Apply core updates and fixes.
|
||||||
|
|
||||||
|
## 2018-12-02 - 1.0.10 - fix(core)
|
||||||
|
Core fixes and maintenance.
|
||||||
|
|
||||||
|
- Apply core updates and fixes.
|
||||||
|
|
||||||
|
## 2018-12-02 - 1.0.9 - test
|
||||||
|
Test updates.
|
||||||
|
|
||||||
|
- Update and improve tests.
|
||||||
|
|
||||||
|
## 2018-09-07 - 1.0.8 - fix(core)
|
||||||
|
Core fixes and maintenance.
|
||||||
|
|
||||||
|
- Apply core updates and fixes.
|
||||||
|
|
||||||
|
## 2018-08-21 - 1.0.7 - fix
|
||||||
|
Remove obsolete logging.
|
||||||
|
|
||||||
|
- Remove obsolete console.log statements.
|
||||||
|
|
||||||
|
## 2018-08-19 - 1.0.6 - ci
|
||||||
|
Continuous integration cleanup.
|
||||||
|
|
||||||
|
- Remove obsolete build dependencies from CI/build configuration.
|
||||||
|
|
||||||
|
## 2018-08-19 - 1.0.5 - dependencies
|
||||||
|
Dependency updates.
|
||||||
|
|
||||||
|
- Update project dependencies.
|
||||||
|
|
||||||
|
## 2018-07-13 - 1.0.4 - package
|
||||||
|
Package metadata fixes.
|
||||||
|
|
||||||
|
- Fix package name in metadata.
|
||||||
|
|
||||||
|
## 2018-07-12 - 1.0.3 - meta
|
||||||
|
Tag-only release.
|
||||||
|
|
||||||
|
- No code changes recorded for this tag (tagging/release bookkeeping only).
|
||||||
|
|
||||||
|
## 2018-07-12 - 1.0.2 - package
|
||||||
|
Project setup.
|
||||||
|
|
||||||
|
- Fix project/package setup issues.
|
||||||
|
|
||||||
|
## 2018-07-12 - 1.0.1 - init
|
||||||
|
Initial release.
|
||||||
|
|
||||||
|
- Initial project release and base setup.
|
24
package.json
24
package.json
@@ -8,23 +8,22 @@
|
|||||||
"author": "Lossless GmbH",
|
"author": "Lossless GmbH",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "(tstest test/)",
|
"test": "(tstest test/ --verbose --logfile --timeout 60)",
|
||||||
"build": "(tsbuild)",
|
"build": "(tsbuild tsfolders)",
|
||||||
"buildDocs": "tsdoc"
|
"buildDocs": "tsdoc"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@gitzone/tsbuild": "^2.1.63",
|
"@git.zone/tsbuild": "^2.1.63",
|
||||||
"@gitzone/tsrun": "^1.2.37",
|
"@git.zone/tsrun": "^1.2.37",
|
||||||
"@gitzone/tstest": "^1.0.71",
|
"@git.zone/tstest": "^2.3.5",
|
||||||
"@pushrocks/tapbundle": "^5.0.3",
|
|
||||||
"@types/node": "^18.0.0"
|
"@types/node": "^18.0.0"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@pushrocks/smartdelay": "^2.0.13",
|
"@push.rocks/smartdelay": "^3.0.5",
|
||||||
"@pushrocks/smarterror": "^2.0.1",
|
"@push.rocks/smarterror": "^2.0.1",
|
||||||
"@pushrocks/smarthash": "^3.0.1",
|
"@push.rocks/smarthash": "^3.0.1",
|
||||||
"@pushrocks/smartpromise": "^3.1.7",
|
"@push.rocks/smartpromise": "^4.2.3",
|
||||||
"@pushrocks/smarttime": "^4.0.1"
|
"@push.rocks/smarttime": "^4.0.1"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"ts/**/*",
|
"ts/**/*",
|
||||||
@@ -58,5 +57,6 @@
|
|||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://code.foss.global/push.rocks/smartcache.git"
|
"url": "https://code.foss.global/push.rocks/smartcache.git"
|
||||||
}
|
},
|
||||||
|
"packageManager": "pnpm@10.14.0+sha512.ad27a79641b49c3e481a16a805baa71817a04bbe06a38d17e60e2eaee83f6a146c6a688125f5792e48dd5ba30e7da52a5cda4c3992b9ccf333f9ce223af84748"
|
||||||
}
|
}
|
10858
pnpm-lock.yaml
generated
10858
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
4
pnpm-workspace.yaml
Normal file
4
pnpm-workspace.yaml
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
onlyBuiltDependencies:
|
||||||
|
- esbuild
|
||||||
|
- mongodb-memory-server
|
||||||
|
- puppeteer
|
318
readme.md
318
readme.md
@@ -1,97 +1,319 @@
|
|||||||
# @push.rocks/smartcache
|
# @push.rocks/smartcache 🚀
|
||||||
Cache things in smart ways.
|
**Smart time-based caching for async functions** - Because waiting is overrated!
|
||||||
|
|
||||||
## Install
|
## 🌟 What is SmartCache?
|
||||||
To use `@push.rocks/smartcache` in your project, you'll need to install it using npm or yarn. Here's how you can do it:
|
|
||||||
|
`@push.rocks/smartcache` is a powerful TypeScript caching library that intelligently caches the results of asynchronous functions. It automatically detects identical function calls based on the call stack, preventing redundant computations and dramatically improving performance. Perfect for expensive API calls, complex calculations, or any async operation you don't want to repeat unnecessarily!
|
||||||
|
|
||||||
|
### ✨ Key Features
|
||||||
|
|
||||||
|
- 🎯 **Automatic cache identification** - Uses smart hashing to detect identical function calls
|
||||||
|
- ⏱️ **Time-based expiration** - Set custom cache durations for each cached operation
|
||||||
|
- 🔄 **Concurrent request handling** - Multiple simultaneous requests for the same data only trigger one actual call
|
||||||
|
- 🎭 **Zero configuration** - Works out of the box with sensible defaults
|
||||||
|
- 📦 **Lightweight** - Minimal dependencies, maximum performance
|
||||||
|
- 🔒 **Type-safe** - Full TypeScript support with proper typing
|
||||||
|
|
||||||
|
## 📦 Installation
|
||||||
|
|
||||||
|
Get started in seconds:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
# Using npm
|
||||||
npm install @push.rocks/smartcache --save
|
npm install @push.rocks/smartcache --save
|
||||||
```
|
|
||||||
or if you are using yarn:
|
|
||||||
|
|
||||||
```bash
|
# Using pnpm (recommended)
|
||||||
|
pnpm add @push.rocks/smartcache
|
||||||
|
|
||||||
|
# Using yarn
|
||||||
yarn add @push.rocks/smartcache
|
yarn add @push.rocks/smartcache
|
||||||
```
|
```
|
||||||
|
|
||||||
## Usage
|
## 🎮 Quick Start
|
||||||
|
|
||||||
`@push.rocks/smartcache` is designed to cache the results of function calls in a smart and efficient way, significantly improving the performance of repeat function calls by avoiding unnecessary recalculations or remote fetches. This package is especially useful when dealing with data that changes infrequently or expensive computation functions whose results can be reused within a given period. Here's how to use `@push.rocks/smartcache` in your TypeScript projects:
|
|
||||||
|
|
||||||
First, make sure to import `SmartCache`:
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { SmartCache } from '@push.rocks/smartcache';
|
import { SmartCache } from '@push.rocks/smartcache';
|
||||||
|
|
||||||
|
// Create a cache instance
|
||||||
|
const cache = new SmartCache();
|
||||||
|
|
||||||
|
// Your expensive async function
|
||||||
|
async function fetchUserData(userId: string) {
|
||||||
|
console.log(`Fetching user ${userId} from API...`);
|
||||||
|
const response = await fetch(`/api/users/${userId}`);
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wrap it with caching - subsequent calls within 5 seconds return cached result
|
||||||
|
async function getCachedUserData(userId: string) {
|
||||||
|
return cache.cacheReturn(
|
||||||
|
() => fetchUserData(userId),
|
||||||
|
5000 // Cache for 5 seconds
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// First call - hits the API
|
||||||
|
const user1 = await getCachedUserData('123'); // Logs: "Fetching user 123 from API..."
|
||||||
|
|
||||||
|
// Second call within 5 seconds - returns cached result instantly!
|
||||||
|
const user2 = await getCachedUserData('123'); // No log, returns cached data
|
||||||
```
|
```
|
||||||
|
|
||||||
### Basic Example
|
## 🚀 Advanced Usage
|
||||||
|
|
||||||
Create an instance of `SmartCache`:
|
### Automatic Call Stack Detection
|
||||||
|
|
||||||
|
SmartCache uses intelligent call stack analysis to automatically identify unique function calls. This means you don't need to manually specify cache keys!
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
const mySmartCache = new SmartCache();
|
const cache = new SmartCache();
|
||||||
```
|
|
||||||
|
|
||||||
Now, imagine you have an asynchronous function whose result you want to cache:
|
// These will be automatically cached separately based on their call location
|
||||||
|
async function getData() {
|
||||||
|
// First location in code
|
||||||
|
const result1 = await cache.cacheReturn(async () => {
|
||||||
|
return await fetch('/api/data1').then(r => r.json());
|
||||||
|
}, 10000);
|
||||||
|
|
||||||
```typescript
|
// Second location in code - different cache entry!
|
||||||
async function fetchData(): Promise<string> {
|
const result2 = await cache.cacheReturn(async () => {
|
||||||
// simulate fetching data
|
return await fetch('/api/data2').then(r => r.json());
|
||||||
await new Promise(resolve => setTimeout(resolve, 1000)); // delay to mimic fetch time
|
}, 10000);
|
||||||
return 'Some fetched data';
|
|
||||||
|
return { result1, result2 };
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Using `@push.rocks/smartcache`, you can cache the result of `fetchData` easily:
|
### Concurrent Request Handling
|
||||||
|
|
||||||
|
SmartCache brilliantly handles concurrent requests - if multiple requests come in for the same cached operation before the first one completes, they all wait for and share the same result:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
async function getCachedData() {
|
const cache = new SmartCache();
|
||||||
const cachedData = await mySmartCache.cacheReturn(fetchData, 60000); // Cache for 1 minute
|
|
||||||
console.log(cachedData); // 'Some fetched data'
|
async function expensiveOperation() {
|
||||||
|
console.log('Starting expensive operation...');
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||||
|
return { data: 'valuable result' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fire off 5 concurrent requests
|
||||||
|
const promises = Array(5).fill(null).map(() =>
|
||||||
|
cache.cacheReturn(expensiveOperation, 60000)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Only ONE "Starting expensive operation..." log appears!
|
||||||
|
// All 5 requests get the same result
|
||||||
|
const results = await Promise.all(promises);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dynamic Cache Durations
|
||||||
|
|
||||||
|
Adjust cache duration based on your data's characteristics:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const cache = new SmartCache();
|
||||||
|
|
||||||
|
async function getDataWithVariableCache(dataType: string) {
|
||||||
|
// Critical data - short cache
|
||||||
|
if (dataType === 'critical') {
|
||||||
|
return cache.cacheReturn(fetchCriticalData, 1000); // 1 second
|
||||||
|
}
|
||||||
|
|
||||||
|
// Static data - long cache
|
||||||
|
if (dataType === 'static') {
|
||||||
|
return cache.cacheReturn(fetchStaticData, 3600000); // 1 hour
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default - moderate cache
|
||||||
|
return cache.cacheReturn(fetchNormalData, 60000); // 1 minute
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Advanced Use Cases
|
### Cache Different Function Results
|
||||||
|
|
||||||
#### Custom Cache Identifiers
|
Each function call location gets its own cache entry:
|
||||||
|
|
||||||
By default, `@push.rocks/smartcache` identifies cache entries based on the call stack. However, when you have dynamic arguments that significantly change the output of the function, you might want to create a custom cache identifier to differentiate between these calls.
|
|
||||||
|
|
||||||
Suppose `fetchData` now takes an argument:
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
async function fetchData(userId: string): Promise<UserData> {
|
const cache = new SmartCache();
|
||||||
// Fetch user data based on userId
|
|
||||||
|
class DataService {
|
||||||
|
async getUserPosts(userId: string) {
|
||||||
|
// Cached separately from getUserProfile
|
||||||
|
return cache.cacheReturn(
|
||||||
|
async () => {
|
||||||
|
const response = await fetch(`/api/users/${userId}/posts`);
|
||||||
|
return response.json();
|
||||||
|
},
|
||||||
|
30000 // Cache for 30 seconds
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUserProfile(userId: string) {
|
||||||
|
// Different cache entry than getUserPosts
|
||||||
|
return cache.cacheReturn(
|
||||||
|
async () => {
|
||||||
|
const response = await fetch(`/api/users/${userId}/profile`);
|
||||||
|
return response.json();
|
||||||
|
},
|
||||||
|
60000 // Cache for 60 seconds
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
You could create a custom cache identifier like so:
|
## 🎯 Real-World Examples
|
||||||
|
|
||||||
|
### API Rate Limiting Helper
|
||||||
|
|
||||||
|
Prevent hitting rate limits by caching API responses:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
const userId = '123';
|
const cache = new SmartCache();
|
||||||
const customIdentifier = `fetchData-${userId}`;
|
|
||||||
|
|
||||||
const cachedUserData = await mySmartCache.cacheReturn(() => fetchData(userId), 60000, customIdentifier);
|
class GitHubService {
|
||||||
|
async getRepoInfo(owner: string, repo: string) {
|
||||||
|
return cache.cacheReturn(
|
||||||
|
async () => {
|
||||||
|
const response = await fetch(
|
||||||
|
`https://api.github.com/repos/${owner}/${repo}`,
|
||||||
|
{ headers: { 'Authorization': `token ${process.env.GITHUB_TOKEN}` } }
|
||||||
|
);
|
||||||
|
return response.json();
|
||||||
|
},
|
||||||
|
300000 // Cache for 5 minutes - respect API limits
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Clearing the Cache
|
### Database Query Optimization
|
||||||
|
|
||||||
In certain situations, you might want to clear the cached data before it expires naturally. `@push.rocks/smartcache` provides a method to manually clear specific cache entries:
|
Cache expensive database queries:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
mySmartCache.clearCache(customIdentifier);
|
const cache = new SmartCache();
|
||||||
|
|
||||||
|
class DatabaseService {
|
||||||
|
async getTopProducts(category: string) {
|
||||||
|
return cache.cacheReturn(
|
||||||
|
async () => {
|
||||||
|
// Expensive aggregation query
|
||||||
|
const products = await db.products.aggregate([
|
||||||
|
{ $match: { category } },
|
||||||
|
{ $group: { _id: '$productId', totalSales: { $sum: '$sales' } } },
|
||||||
|
{ $sort: { totalSales: -1 } },
|
||||||
|
{ $limit: 10 }
|
||||||
|
]);
|
||||||
|
return products;
|
||||||
|
},
|
||||||
|
120000 // Cache for 2 minutes - data doesn't change often
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Best Practices
|
### Computed Values Cache
|
||||||
|
|
||||||
- **Cache Duration**: Choose a cache duration that makes sense for your data. Highly dynamic data might not benefit much from long cache times, whereas static data can be cached longer.
|
Cache expensive computations:
|
||||||
- **Error Handling**: Always implement error handling for your cached functions, especially when dealing with network requests.
|
|
||||||
- **Memory Management**: Be mindful of what you cache. Caching large objects or a high number of entries can lead to increased memory usage.
|
|
||||||
|
|
||||||
### Conclusion
|
```typescript
|
||||||
|
const cache = new SmartCache();
|
||||||
|
|
||||||
`@push.rocks/smartcache` is a powerful utility for caching asynchronous function results, significantly improving the performance and efficiency of your applications. By understanding and implementing the basics and exploring advanced use cases, you can leverage `@push.rocks/smartcache` to its full potential.
|
class AnalyticsService {
|
||||||
|
async calculateMetrics(data: number[]) {
|
||||||
|
return cache.cacheReturn(
|
||||||
|
async () => {
|
||||||
|
console.log('Running expensive calculation...');
|
||||||
|
// Simulate expensive computation
|
||||||
|
const result = {
|
||||||
|
mean: data.reduce((a, b) => a + b, 0) / data.length,
|
||||||
|
median: this.calculateMedian(data),
|
||||||
|
standardDeviation: this.calculateStdDev(data),
|
||||||
|
percentiles: this.calculatePercentiles(data)
|
||||||
|
};
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
600000 // Cache for 10 minutes
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Remember, the key to effective caching is understanding your data's behavior and aligning your caching strategy accordingly. Happy caching!
|
private calculateMedian(data: number[]) { /* ... */ }
|
||||||
|
private calculateStdDev(data: number[]) { /* ... */ }
|
||||||
|
private calculatePercentiles(data: number[]) { /* ... */ }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📊 Performance Benefits
|
||||||
|
|
||||||
|
SmartCache can dramatically improve your application's performance:
|
||||||
|
|
||||||
|
- 🚀 **Reduce API calls** by up to 90% for frequently accessed data
|
||||||
|
- ⚡ **Instant responses** for cached data (sub-millisecond)
|
||||||
|
- 📉 **Lower server costs** by reducing redundant computations
|
||||||
|
- 🛡️ **Protect against thundering herd** problems
|
||||||
|
- 🔄 **Automatic cleanup** - expired cache entries are removed automatically
|
||||||
|
|
||||||
|
## 🏗️ Architecture & How It Works
|
||||||
|
|
||||||
|
SmartCache uses a sophisticated approach to caching:
|
||||||
|
|
||||||
|
1. **Call Stack Hashing**: When you call `cacheReturn`, SmartCache captures the call stack and generates a SHA-256 hash
|
||||||
|
2. **Cache Lookup**: It checks if a valid cached result exists for this hash
|
||||||
|
3. **Concurrent Protection**: If a request is in-flight, new requests wait for the same result
|
||||||
|
4. **Automatic Expiration**: Each cache entry has a timer that automatically removes it when expired
|
||||||
|
5. **Memory Efficient**: Only stores what's actively being used, expired entries are cleaned up
|
||||||
|
|
||||||
|
## 💡 Best Practices
|
||||||
|
|
||||||
|
### ✅ Do's
|
||||||
|
|
||||||
|
- **Cache expensive operations** - API calls, database queries, complex calculations
|
||||||
|
- **Use appropriate durations** - Match cache time to your data's update frequency
|
||||||
|
- **Cache at the right level** - Cache complete results, not partial data
|
||||||
|
- **Monitor memory usage** - Be mindful when caching large objects
|
||||||
|
|
||||||
|
### ❌ Don'ts
|
||||||
|
|
||||||
|
- **Don't cache user-specific sensitive data** without careful consideration
|
||||||
|
- **Don't use excessive cache durations** for frequently changing data
|
||||||
|
- **Don't cache massive objects** that could cause memory issues
|
||||||
|
- **Don't rely on cache** for critical data consistency
|
||||||
|
|
||||||
|
## 🎓 Pro Tips
|
||||||
|
|
||||||
|
1. **Layer your caching**: Use SmartCache alongside CDN and database caching for maximum effect
|
||||||
|
2. **Cache warming**: Pre-populate cache with frequently accessed data on startup
|
||||||
|
3. **Metrics tracking**: Monitor cache hit rates to optimize cache durations
|
||||||
|
4. **Error handling**: Always handle potential errors in cached functions
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const cache = new SmartCache();
|
||||||
|
|
||||||
|
// Good - with error handling
|
||||||
|
async function getResilientData() {
|
||||||
|
return cache.cacheReturn(
|
||||||
|
async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/data');
|
||||||
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||||
|
return response.json();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch data:', error);
|
||||||
|
// Return fallback or rethrow based on your needs
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
30000
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🤝 Support & Community
|
||||||
|
|
||||||
|
- 🐛 **Found a bug?** [Open an issue](https://code.foss.global/push.rocks/smartcache/issues)
|
||||||
|
- 💡 **Have a feature request?** [Start a discussion](https://code.foss.global/push.rocks/smartcache/issues)
|
||||||
|
- 📖 **Need help?** Check our [comprehensive documentation](https://code.foss.global/push.rocks/smartcache)
|
||||||
|
|
||||||
## License and Legal Information
|
## License and Legal Information
|
||||||
|
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
import { expect, tap } from '@pushrocks/tapbundle';
|
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||||
import * as smartcache from '../ts/index.js';
|
import * as smartcache from '../ts/index.js';
|
||||||
|
|
||||||
let smartcacheInstance: smartcache.SmartCache;
|
let smartcacheInstance: smartcache.SmartCache;
|
||||||
|
@@ -1,8 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* autocreated commitinfo by @pushrocks/commitinfo
|
* autocreated commitinfo by @push.rocks/commitinfo
|
||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@pushrocks/smartcache',
|
name: '@push.rocks/smartcache',
|
||||||
version: '1.0.16',
|
version: '1.0.17',
|
||||||
description: 'cache things in smart ways'
|
description: 'A module for caching asynchronous function results with smart time and hash-based invalidation strategies.'
|
||||||
}
|
}
|
||||||
|
@@ -1,5 +1,5 @@
|
|||||||
import * as plugins from './smartcache.plugins.js';
|
import * as plugins from './smartcache.plugins.js';
|
||||||
import { SmartError } from '@pushrocks/smarterror';
|
import { SmartError } from '@push.rocks/smarterror';
|
||||||
|
|
||||||
export interface ICacheMap {
|
export interface ICacheMap {
|
||||||
[key: string]: {
|
[key: string]: {
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
import * as smartdelay from '@pushrocks/smartdelay';
|
import * as smartdelay from '@push.rocks/smartdelay';
|
||||||
import * as smarterror from '@pushrocks/smarterror';
|
import * as smarterror from '@push.rocks/smarterror';
|
||||||
import * as smartpromise from '@pushrocks/smartpromise';
|
import * as smartpromise from '@push.rocks/smartpromise';
|
||||||
import * as smarttime from '@pushrocks/smarttime';
|
import * as smarttime from '@push.rocks/smarttime';
|
||||||
import * as smarthash from '@pushrocks/smarthash';
|
import * as smarthash from '@push.rocks/smarthash';
|
||||||
|
|
||||||
export { smarterror, smartdelay, smartpromise, smarttime, smarthash };
|
export { smarterror, smartdelay, smartpromise, smarttime, smarthash };
|
||||||
|
Reference in New Issue
Block a user