Compare commits

..

No commits in common. "master" and "v1.0.13" have entirely different histories.

17 changed files with 1755 additions and 4568 deletions

4
.gitignore vendored
View File

@ -15,6 +15,8 @@ node_modules/
# builds # builds
dist/ dist/
dist_*/ dist_web/
dist_serve/
dist_ts_web/
# custom # custom

View File

@ -12,9 +12,6 @@ stages:
- release - release
- metadata - metadata
before_script:
- npm install -g @shipzone/npmci
# ==================== # ====================
# security stage # security stage
# ==================== # ====================
@ -22,36 +19,22 @@ mirror:
stage: security stage: security
script: script:
- npmci git mirror - npmci git mirror
only:
- tags
tags: tags:
- lossless - lossless
- docker - docker
- notpriv - notpriv
auditProductionDependencies: snyk:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci image: registry.gitlab.com/hosttoday/ht-docker-node:snyk
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 stage: security
script: script:
- npmci npm prepare - npmci npm prepare
- npmci command npm install --ignore-scripts - npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org - npmci command snyk test
- npmci command npm audit --audit-level=high --only=dev
tags: tags:
- lossless
- docker - docker
allow_failure: true - notpriv
# ==================== # ====================
# test stage # test stage
@ -66,7 +49,9 @@ testStable:
- npmci npm test - npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/ coverage: /\d+.?\d+?\%\s*coverage/
tags: tags:
- lossless
- docker - docker
- priv
testBuild: testBuild:
stage: test stage: test
@ -77,7 +62,9 @@ testBuild:
- npmci command npm run build - npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/ coverage: /\d+.?\d+?\%\s*coverage/
tags: tags:
- lossless
- docker - docker
- notpriv
release: release:
stage: release stage: release
@ -97,12 +84,11 @@ release:
codequality: codequality:
stage: metadata stage: metadata
allow_failure: true allow_failure: true
only:
- tags
script: script:
- npmci command npm install -g typescript - npmci command npm install -g tslint typescript
- npmci npm prepare - npmci npm prepare
- npmci npm install - npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags: tags:
- lossless - lossless
- docker - docker
@ -122,10 +108,11 @@ trigger:
pages: pages:
stage: metadata stage: metadata
script: script:
- npmci node install stable - npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare - npmci npm prepare
- npmci npm install - npmci npm install
- npmci command npm run buildDocs - npmci command tsdoc
tags: tags:
- lossless - lossless
- docker - docker

24
.vscode/launch.json vendored
View File

@ -2,10 +2,28 @@
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"command": "npm test", "name": "current file",
"name": "Run npm test", "type": "node",
"request": "launch", "request": "launch",
"type": "node-terminal" "args": [
"${relativeFile}"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "test.ts",
"type": "node",
"request": "launch",
"args": [
"test/test.ts"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
} }
] ]
} }

View File

@ -15,7 +15,7 @@
"properties": { "properties": {
"projectType": { "projectType": {
"type": "string", "type": "string",
"enum": ["website", "element", "service", "npm", "wcc"] "enum": ["website", "element", "service", "npm"]
} }
} }
} }

View File

@ -6,27 +6,12 @@
"gitzone": { "gitzone": {
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "code.foss.global", "githost": "gitlab.com",
"gitscope": "push.rocks", "gitscope": "pushrocks",
"gitrepo": "smartcache", "gitrepo": "smartcache",
"description": "A module for caching asynchronous function results with smart time and hash-based invalidation strategies.", "shortDescription": "cache things in smart ways",
"npmPackagename": "@push.rocks/smartcache", "npmPackagename": "@pushrocks/smartcache",
"license": "MIT", "license": "MIT"
"keywords": [
"caching",
"asynchronous",
"time-based invalidation",
"hash-based identification",
"smart caching",
"node.js",
"performance optimization",
"typescript",
"delay handling",
"error management"
]
} }
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
} }
} }

1635
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,62 +1,41 @@
{ {
"name": "@push.rocks/smartcache", "name": "@pushrocks/smartcache",
"version": "1.0.16", "version": "1.0.13",
"private": false, "private": false,
"description": "A module for caching asynchronous function results with smart time and hash-based invalidation strategies.", "description": "cache things in smart ways",
"main": "dist_ts/index.js", "main": "dist/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist/index.d.ts",
"author": "Lossless GmbH", "author": "Lossless GmbH",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "(tstest test/)",
"build": "(tsbuild)", "build": "(tsbuild)"
"buildDocs": "tsdoc"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.63", "@gitzone/tsbuild": "^2.1.17",
"@gitzone/tsrun": "^1.2.37", "@gitzone/tsrun": "^1.2.8",
"@gitzone/tstest": "^1.0.71", "@gitzone/tstest": "^1.0.28",
"@pushrocks/tapbundle": "^5.0.3", "@pushrocks/tapbundle": "^3.2.0",
"@types/node": "^18.0.0" "@types/node": "^13.7.0",
"tslint": "^6.0.0",
"tslint-config-prettier": "^1.18.0"
}, },
"dependencies": { "dependencies": {
"@pushrocks/smartdelay": "^2.0.13", "@pushrocks/smartdelay": "^2.0.6",
"@pushrocks/smarterror": "^2.0.1", "@pushrocks/smarterror": "^2.0.1",
"@pushrocks/smarthash": "^3.0.1", "@pushrocks/smarthash": "^2.1.6",
"@pushrocks/smartpromise": "^3.1.7", "@pushrocks/smartpromise": "^3.0.6",
"@pushrocks/smarttime": "^4.0.1" "@pushrocks/smarttime": "^3.0.12"
}, },
"files": [ "files": [
"ts/**/*", "ts/**/*",
"ts_web/**/*", "ts_web/**/*",
"dist/**/*", "dist/**/*",
"dist_*/**/*", "dist_web/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*", "dist_ts_web/**/*",
"assets/**/*", "assets/**/*",
"cli.js", "cli.js",
"npmextra.json", "npmextra.json",
"readme.md" "readme.md"
], ]
"browserslist": [
"last 1 chrome versions"
],
"type": "module",
"keywords": [
"caching",
"asynchronous",
"time-based invalidation",
"hash-based identification",
"smart caching",
"node.js",
"performance optimization",
"typescript",
"delay handling",
"error management"
],
"homepage": "https://code.foss.global/push.rocks/smartcache",
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/smartcache.git"
}
} }

4326
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@

124
readme.md
View File

@ -1,113 +1,31 @@
# @push.rocks/smartcache # @pushrocks/smartcache
Cache things in smart ways. cache things in smart ways
## Install ## Availabililty and Links
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: * [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartcache)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartcache)
* [github.com (source mirror)](https://github.com/pushrocks/smartcache)
* [docs (typedoc)](https://pushrocks.gitlab.io/smartcache/)
```bash ## Status for master
npm install @push.rocks/smartcache --save [![pipeline status](https://gitlab.com/pushrocks/smartcache/badges/master/pipeline.svg)](https://gitlab.com/pushrocks/smartcache/commits/master)
``` [![coverage report](https://gitlab.com/pushrocks/smartcache/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smartcache/commits/master)
or if you are using yarn: [![npm downloads per month](https://img.shields.io/npm/dm/@pushrocks/smartcache.svg)](https://www.npmjs.com/package/@pushrocks/smartcache)
[![Known Vulnerabilities](https://snyk.io/test/npm/@pushrocks/smartcache/badge.svg)](https://snyk.io/test/npm/@pushrocks/smartcache)
```bash [![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
yarn add @push.rocks/smartcache [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
``` [![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/)
## Usage ## Usage
`@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`: ## Contribution
```typescript We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
import { SmartCache } from '@push.rocks/smartcache';
```
### Basic Example For further information read the linked docs at the top of this readme.
Create an instance of `SmartCache`: > MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
```typescript [![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)
const mySmartCache = new SmartCache();
```
Now, imagine you have an asynchronous function whose result you want to cache:
```typescript
async function fetchData(): Promise<string> {
// simulate fetching data
await new Promise(resolve => setTimeout(resolve, 1000)); // delay to mimic fetch time
return 'Some fetched data';
}
```
Using `@push.rocks/smartcache`, you can cache the result of `fetchData` easily:
```typescript
async function getCachedData() {
const cachedData = await mySmartCache.cacheReturn(fetchData, 60000); // Cache for 1 minute
console.log(cachedData); // 'Some fetched data'
}
```
### Advanced Use Cases
#### Custom Cache Identifiers
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
async function fetchData(userId: string): Promise<UserData> {
// Fetch user data based on userId
}
```
You could create a custom cache identifier like so:
```typescript
const userId = '123';
const customIdentifier = `fetchData-${userId}`;
const cachedUserData = await mySmartCache.cacheReturn(() => fetchData(userId), 60000, customIdentifier);
```
#### Clearing the Cache
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:
```typescript
mySmartCache.clearCache(customIdentifier);
```
### Best Practices
- **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.
- **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
`@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.
Remember, the key to effective caching is understanding your data's behavior and aligning your caching strategy accordingly. Happy caching!
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@ -1,38 +1,35 @@
import { expect, tap } from '@pushrocks/tapbundle'; import { expect, tap } from '@pushrocks/tapbundle';
import * as smartcache from '../ts/index.js'; import * as smartcache from '../ts/index';
import * as smartdelay from '@pushrocks/smartdelay';
let smartcacheInstance: smartcache.SmartCache; let smartcacheInstance: smartcache.SmartCache;
tap.test('should create a valid instance of SmartCache', async () => { tap.test('should create a valid instance of SmartCache', async () => {
smartcacheInstance = new smartcache.SmartCache(); smartcacheInstance = new smartcache.SmartCache();
expect(smartcacheInstance).toBeInstanceOf(smartcache.SmartCache); expect(smartcacheInstance).to.be.instanceof(smartcache.SmartCache);
}); });
tap.test('try to get async responses', async (toolsArg) => { tap.test('try to get async responses', async () => {
let response1Counter = 0;
const getResponse = async () => { const getResponse = async () => {
const response = await smartcacheInstance const response = await smartcacheInstance
.cacheReturn(async () => { .cacheReturn(async () => {
console.log('function 1 ran'); console.log('function 1 ran');
response1Counter++;
return 'hello'; return 'hello';
}, 1000) }, 1000)
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
}); });
console.log('response is:'); console.log('response is:');
console.log(response); console.log(response);
}; };
let response2Counter = 0;
const getResponse2 = async () => { const getResponse2 = async () => {
const response = await smartcacheInstance const response = await smartcacheInstance
.cacheReturn(async () => { .cacheReturn(async () => {
console.log('function 2 ran'); console.log('function 2 ran');
response2Counter++;
return 'hello there!'; return 'hello there!';
}, 1000) }, 1000)
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
}); });
console.log('response is:'); console.log('response is:');
@ -43,12 +40,12 @@ tap.test('try to get async responses', async (toolsArg) => {
await getResponse(); await getResponse();
await getResponse2(); await getResponse2();
await getResponse2(); await getResponse2();
await toolsArg.delayFor(500); await smartdelay.delayFor(2000).then(async () => {
await getResponse(); await getResponse();
await toolsArg.delayFor(2000);
await getResponse2(); await getResponse2();
});
}); });
tap.start({ tap.start({
throwOnError: true, throwOnError: true
}); });

View File

@ -1,8 +0,0 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
*/
export const commitinfo = {
name: '@pushrocks/smartcache',
version: '1.0.16',
description: 'cache things in smart ways'
}

View File

@ -1 +1 @@
export * from './smartcache.classes.smartcache.js'; export * from './smartcache.classes.smartcache';

View File

@ -1,4 +1,4 @@
import * as plugins from './smartcache.plugins.js'; import * as plugins from './smartcache.plugins';
import { SmartError } from '@pushrocks/smarterror'; import { SmartError } from '@pushrocks/smarterror';
export interface ICacheMap { export interface ICacheMap {
@ -12,7 +12,7 @@ export interface ICacheMap {
export class CacheManager { export class CacheManager {
private _cacheMap: ICacheMap = {}; private _cacheMap: ICacheMap = {};
cacheExists(identifierArg: string): boolean { cacheExists(identifierArg): boolean {
if (this._cacheMap[identifierArg]) { if (this._cacheMap[identifierArg]) {
return true; return true;
} }
@ -36,7 +36,7 @@ export class CacheManager {
this._cacheMap[identifierArg] = { this._cacheMap[identifierArg] = {
timer: new plugins.smarttime.Timer(validForArg), timer: new plugins.smarttime.Timer(validForArg),
cachedDeferred: new plugins.smartpromise.Deferred(), cachedDeferred: new plugins.smartpromise.Deferred(),
cachedObject: null, cachedObject: null
}; };
this._cacheMap[identifierArg].timer.start(); this._cacheMap[identifierArg].timer.start();
this._cacheMap[identifierArg].timer.completed.then(() => { this._cacheMap[identifierArg].timer.completed.then(() => {

View File

@ -1,13 +1,11 @@
import * as plugins from './smartcache.plugins.js'; import * as plugins from './smartcache.plugins';
import { CacheManager } from './smartcache.classes.cachemanager.js'; import { CacheManager } from './smartcache.classes.cachemanager';
export class SmartCache { export class SmartCache {
private _cacheManager = new CacheManager(); private _cacheManager = new CacheManager();
async cacheReturn(asyncCachedFuncArg: () => Promise<any>, cacheDuration: number = 5000) { async cacheReturn(asyncCachedFuncArg: () => Promise<any>, cacheDuration: number = 5000) {
const callStack: string = new plugins.smarterror.SmartError( const callStack: string = new plugins.smarterror.SmartError('Cache Creation Point').cleanFullStack.split('\n')[2];
'Cache Creation Point'
).cleanFullStack.split('\n')[2];
const callHash = plugins.smarthash.sha256FromStringSync(callStack); const callHash = plugins.smarthash.sha256FromStringSync(callStack);
// console.log(callHash); // console.log(callHash);

View File

@ -1,14 +0,0 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

17
tslint.json Normal file
View File

@ -0,0 +1,17 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}