https://github.com/kbismark/cachestorage
A lightweight wrapper around the Cache API for performing CRUD operations in the browser.
https://github.com/kbismark/cachestorage
cache-storage javascript localstorage typescript web-development
Last synced: 4 months ago
JSON representation
A lightweight wrapper around the Cache API for performing CRUD operations in the browser.
- Host: GitHub
- URL: https://github.com/kbismark/cachestorage
- Owner: KBismark
- License: mit
- Created: 2025-01-16T03:17:02.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2025-02-24T00:44:46.000Z (over 1 year ago)
- Last Synced: 2025-11-02T00:17:24.907Z (8 months ago)
- Topics: cache-storage, javascript, localstorage, typescript, web-development
- Language: TypeScript
- Homepage:
- Size: 59.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://badge.fury.io/js/@codigex%2Fcachestorage)
[](https://www.npmjs.com/package/@codigex%2Fcachestorage)
[](https://opensource.org/licenses/MIT)
# Cache Local Storage
A better way to save data locally on the browser. Think about using the browser's cache system as your local storage space in your applications.
## Why Cache Local Storage?
If browsers can cache resources like images, javascript files, and many more, why not use it to store your application data?
Cache Local Storage is a library that helps you store and retrieve data in the browser's cache system. Compared to local storage or session storage, It has a larger storage capacity and also asynchronous. It also provides features like schema validation, compression, and encryption. No need for server interverntion to cache data, it is all done on the client side. Store, retrieve, update, and delete data with ease.
Use Cache Local Storage to store data like user settings, user preferences, user data, and many more. It is a great way to store data that should persist even when the browser is closed.
## Features
- **Schema Validation**: Validate data before storing it. *Optional*
- **Compression**: Compress data before storing it. *Optional*
- **Encryption**: Encrypt data before storing it. *Optional*
- **Cache Duration**: Set a duration for how long data should be stored. Defaults to a year.
- **More Persistent**: Data is stored in the browser's cache system which is more persistent than local storage.
- **Larger Storage Capacity**: Set a maximum size for the storage. Defaults to 50MB.
## Installation
```bash
npm install @codigex/cachestorage
```
## How to use
First, import the library and initialize it with options. Then you can store, retrieve, update, and delete data with ease.
```js
import CacheLocalStorage from '@codigex/cachestorage';
// Initialize storage with options
const storage = new CacheLocalStorage({
maxSize: 100 * 1024 * 1024, // 100MB - Default is 50MB
namespace: "my-app",
cacheDuration: 86400, // 1 day - Default is 1 year
});
```
### Storing data without schema validation
```js
// Store user data without schema validation
async function storeUser(user) {
const result = await storage.setItem(user.id, user);
if (result.success) {
console.log("User stored:", result.data);
} else {
console.error("Storage failed:", result.error);
}
}
```
### Getting data
```js
// Retrieve user data
async function getUser(userId) {
const result = await storage.getItem(userId);
return result.data || null;
}
```
### Updating data
Update data in the cache. Uses `setItem` internally.
```js
// Update fields in user data
async function updateUserName(userId, newName) {
const result = await storage.updateItem(userId, { name: newName });
if (result.success) {
console.log("User updated:", result.data);
} else {
console.error("Update failed:", result.error);
}
}
```
### Check storage stats
You can check the storage stats to know how much space is used and how much is available.
```js
// Check storage stats
async function checkStorage() {
const stats = await storage.getStats();
console.log(`Storage usage: ${stats.percentUsed.toFixed(2)}%`);
console.log(`Available: ${(stats.available / 1024 / 1024).toFixed(2)}MB`);
}
```
### Basic usage
```js
// Example usage
async function example() {
const user = {
id: "dXNlcjoxMjM0NTY3ODkw",
name: "John Doe",
email: "john@example.com",
};
await storeUser(user); // Store user data
const storedUser = await getUser(user.id); // Retrieve user data
if (storedUser) {
console.log("Retrieved user: ", storedUser);
}else{
console.log("No user found");
}
await updateUserName(user.id, "James Season"); // Update user data
await checkStorage();
}
```
## Usage with more advanced features
You can use schema validation, compression, and encryption with Cache Local Storage.
```js
import CacheLocalStorage from '@codigex/cachestorage';
// Initialize storage with options
const storage = new CacheLocalStorage({
maxSize: 100 * 1024 * 1024, // 100MB
namespace: "my-app",
cacheDuration: 86400, // 1 day - Default is 1 year
compression: { enabled: true, level: 9 }, // Set compression configs - optional
encryptionKey: "0123456789abcdef0123456789abcdef", // 32 or 64 bytes key for encryption - optional
});
// Initialize schema for validation - optional
const userSchema = {
id: {
type: "string",
required: true,
validate: (value) => value.length > 0,
},
name: {
type: "string",
required: true,
validate: (value) => value.length > 0,
},
email: {
type: "string",
required: true,
validate: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
},
};
// Store user data with schema validation
async function storeUser(user) {
const result = await storage.setItem(user.id, user, userSchema);
if (result.success) {
console.log("User stored:", result.data);
} else {
console.error("Storage failed:", result.error);
}
}
// Retrieve user data
async function getUser(userId) {
const result = await storage.getItem(userId);
return result.data || null;
}
// Update fields in user data
async function updateUserName(userId, newName) {
const result = await storage.updateItem(userId, { name: newName }, userSchema);
if (result.success) {
console.log("User updated:", result.data);
} else {
console.error("Update failed:", result.error);
}
}
async function example() {
const user = {
id: "dXNlcjoxMjM0NTY3ODkw",
name: "John Doe",
email: "john@example.com",
};
try {
await storeUser(user);
} catch (error) {
console.error("Error storing user: ", error);
}
try {
const storedUser = await getUser(user.id);
if (storedUser) {
console.log("Retrieved user: ", storedUser);
}else{
console.log("No user found");
}
} catch (error) {
console.error("Error retrieving user: ", error);
}
try {
await updateUserName(user.id, "James Season");
} catch (error) {
console.error("Error updating user: ", error);
}
}
example();
```
## API
### CacheLocalStorage
- **constructor(options: CacheLocalStorageOptions): CacheLocalStorage** - Initialize Cache Local Storage with options.
- **setItem(key: string, data: any, schema?: Schema): Promise** - Store data in cache.
- **key**: string - The key to store the data with.
- **data**: any - The data to store.
- **schema**: Schema - The schema to validate the data with. *Optional*
- **getItem(key: string): Promise** - Retrieve data from cache.
- **key**: string - The key to retrieve the data with.
- **updateItem(key: string, data: any, schema?: Schema): Promise** - Update data in cache. Uses `setItem` internally.
- **key**: string - The key to update the data with.
- **data**: any - The data to update.
- **schema**: Schema - The schema to validate the data with. *Optional*
- **removeItem(key: string): Promise** - Remove data from cache.
- **key**: string - The key to remove the data with.
- **clear(): Promise** - Clear all data from cache.
- **getStats(): Promise** - Get storage stats.
- **getCompressionStats(key: string): Promise** - Get compression stats.
## Limitations
- **Storage Capacity**: Cache Local Storage is limited by the browser's cache system.
- **Data Persistence**: Browser cache can be cleared by the user or the browser.
- **Data Security**: Data stored in the browser cache is not secure. It is recommended not to store anything sensitive on the user browser. However, if you still do, then enable encryption.