A lightweight utility for efficient patching and pruning of objects in JavaScript/TypeScript state trees.
npm install resource-state-managementjson
{
"id": 1,
"integrity": "company-1",
"name": "ACME Corp",
"employees": [
{
"id": 2,
"integrity": "employee-2",
"name": "John Doe"
}
]
}
`
📦 Installation
Install the package using npm:
`bash
npm install resource-state-management
`
🔗 Generating and Using Integrity Keys
An integrity key is a unique code for each object in your state tree. It helps keep things consistent and avoids errors.
$3
- Consistency: The same object will always have the same key.
- Avoiding Conflicts: A good key avoids mistakes where two different objects get the same key.
- No Extra Tools Needed: You don’t need extra counters or unique ID generators—the key comes directly from the object’s data.
$3
#### In JavaScript:
`javascript
import md5 from 'md5';
function calculateResourceIntegrity(objectType, id) {
return md5(${objectType}-${id});
}
`
#### In PHP:
`php
function calculateResourceIntegrity(string $objectType, int $id) {
return md5("$objectType-$id");
}
`
⚙️ API Usage
$3
- Recursively scans an object or array and builds a Map of all nested resources.
$3
- Merges (shallow spread) matched objects from the resource map into the state tree and returns a new tree.
$3
- Removes any nested object whose integrity matches the provided integrity key, and prunes undefined values from the tree.
⚡️ Example Integration with SWR
Here's how you can integrate resource-state-management into an SWR-based application:
`diff
import { mutate } from 'swr';
+ import { collectResourceMap, patchResources, pruneResources } from 'resource-state-management';
+ async function patchResource(response: any) {
+ const map = collectResourceMap(response);
+ await mutate(
+ () => true, // Update global state
+ (cache: any) => patchResources(cache, map),
+ false
+ );
+ }
+ async function pruneResource(key: string) {
+ await mutate(
+ () => true,
+ (cache: any) => pruneResources(cache, key),
+ false
+ );
+ }
export async function createCompany(data) {
const response = await api.createCompany(data);
await mutate(
"api/companies",
(cache: any) => [response, ...cache],
false
);
}
export async function updateCompany(data) {
const response = await api.updateCompany(data);
+ await patchResource(response);
- await mutate(
- "api/companies",
- (cache: any) => cache.map(company => company.id === response.id ? response : company),
- false
- );
}
async function deleteCompany(company) {
const response = await api.deleteCompany(company);
- await mutate(
- "api/companies",
- (currentData: any) => currentData.filter(company => company.id !== response.id),
- false
- );
+ await pruneResource(response);
}
`
🔍 Performance & Best Practices
- Batch Updates: Apply multiple integrity patches in a single patchResources call for better performance.
- Selective Mutations: Target specific SWR cache keys instead of global state (() => true`).