@fjell/cache 4.6.13 → 4.6.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/Aggregator.d.ts +3 -3
  2. package/dist/Cache.d.ts +6 -6
  3. package/dist/CacheMap.d.ts +1 -1
  4. package/dist/Instance.d.ts +5 -5
  5. package/dist/InstanceFactory.d.ts +3 -3
  6. package/dist/Operations.d.ts +4 -4
  7. package/dist/index.js +715 -0
  8. package/dist/index.js.map +7 -0
  9. package/dist/logger.d.ts +1 -1
  10. package/dist/ops/action.d.ts +3 -3
  11. package/dist/ops/all.d.ts +3 -3
  12. package/dist/ops/allAction.d.ts +3 -3
  13. package/dist/ops/allFacet.d.ts +3 -3
  14. package/dist/ops/create.d.ts +3 -3
  15. package/dist/ops/facet.d.ts +3 -3
  16. package/dist/ops/find.d.ts +3 -3
  17. package/dist/ops/findOne.d.ts +3 -3
  18. package/dist/ops/get.d.ts +3 -3
  19. package/dist/ops/one.d.ts +3 -3
  20. package/dist/ops/remove.d.ts +3 -3
  21. package/dist/ops/reset.d.ts +3 -3
  22. package/dist/ops/retrieve.d.ts +3 -3
  23. package/dist/ops/set.d.ts +2 -2
  24. package/dist/ops/update.d.ts +3 -3
  25. package/package.json +8 -12
  26. package/dist/Aggregator.cjs.js +0 -322
  27. package/dist/Aggregator.es.js +0 -317
  28. package/dist/Cache.cjs.js +0 -35
  29. package/dist/Cache.es.js +0 -30
  30. package/dist/CacheMap.cjs.js +0 -170
  31. package/dist/CacheMap.es.js +0 -166
  32. package/dist/Instance.cjs.js +0 -23
  33. package/dist/Instance.es.js +0 -18
  34. package/dist/InstanceFactory.cjs.js +0 -35
  35. package/dist/InstanceFactory.es.js +0 -31
  36. package/dist/Operations.cjs.js +0 -43
  37. package/dist/Operations.es.js +0 -39
  38. package/dist/Registry.cjs.js +0 -36
  39. package/dist/Registry.es.js +0 -31
  40. package/dist/index.cjs +0 -940
  41. package/dist/index.cjs.js +0 -26
  42. package/dist/index.cjs.map +0 -1
  43. package/dist/index.es.js +0 -8
  44. package/dist/logger.cjs.js +0 -10
  45. package/dist/logger.es.js +0 -6
  46. package/dist/ops/action.cjs.js +0 -28
  47. package/dist/ops/action.es.js +0 -24
  48. package/dist/ops/all.cjs.js +0 -33
  49. package/dist/ops/all.es.js +0 -29
  50. package/dist/ops/allAction.cjs.js +0 -35
  51. package/dist/ops/allAction.es.js +0 -31
  52. package/dist/ops/allFacet.cjs.js +0 -22
  53. package/dist/ops/allFacet.es.js +0 -18
  54. package/dist/ops/create.cjs.js +0 -23
  55. package/dist/ops/create.es.js +0 -19
  56. package/dist/ops/facet.cjs.js +0 -21
  57. package/dist/ops/facet.es.js +0 -17
  58. package/dist/ops/find.cjs.js +0 -26
  59. package/dist/ops/find.es.js +0 -22
  60. package/dist/ops/findOne.cjs.js +0 -24
  61. package/dist/ops/findOne.es.js +0 -20
  62. package/dist/ops/get.cjs.js +0 -38
  63. package/dist/ops/get.es.js +0 -34
  64. package/dist/ops/one.cjs.js +0 -33
  65. package/dist/ops/one.es.js +0 -29
  66. package/dist/ops/remove.cjs.js +0 -30
  67. package/dist/ops/remove.es.js +0 -26
  68. package/dist/ops/reset.cjs.js +0 -15
  69. package/dist/ops/reset.es.js +0 -11
  70. package/dist/ops/retrieve.cjs.js +0 -37
  71. package/dist/ops/retrieve.es.js +0 -33
  72. package/dist/ops/set.cjs.js +0 -71
  73. package/dist/ops/set.es.js +0 -67
  74. package/dist/ops/update.cjs.js +0 -34
  75. package/dist/ops/update.es.js +0 -30
  76. package/docs/docs.config.ts +0 -75
  77. package/docs/index.html +0 -18
  78. package/docs/package.json +0 -34
  79. package/docs/public/README.md +0 -96
  80. package/docs/public/examples-README.md +0 -302
  81. package/docs/public/test.txt +0 -0
  82. package/docs/src/index.css +0 -3
  83. package/docs/src/main.tsx +0 -12
  84. package/docs/src/test/setup.ts +0 -1
  85. package/docs/tsconfig.node.json +0 -15
  86. package/examples/README.md +0 -302
  87. package/examples/aggregator-example.ts +0 -329
  88. package/examples/basic-cache-example.ts +0 -270
  89. package/examples/cache-map-example.ts +0 -265
  90. package/vitest.config.ts +0 -44
@@ -1,302 +0,0 @@
1
- # Fjell-Cache Examples
2
-
3
- This directory contains examples demonstrating how to use fjell-cache for caching data models and managing complex business relationships with different patterns and complexity levels.
4
-
5
- ## Examples
6
-
7
- ### 1. `basic-cache-example.ts` ⭐ **Start Here!**
8
- **Perfect for beginners!** Demonstrates the fundamental way to use fjell-cache for data caching:
9
- - **Basic cache operations** - Create caches with coordinates and registries, use operations API
10
- - **Simple data models** - User and Task entities with mock storage
11
- - **Cache-as-Instance architecture** - Caches extend Instance from fjell-registry
12
- - **Cache hits vs misses** - Understand cache behavior and performance benefits
13
- - **Cache management** - Updates, deletions, and data consistency through operations
14
-
15
- Great for understanding the fundamentals of fjell-cache data management.
16
-
17
- ### 2. `aggregator-example.ts` 🏗️ **Advanced Business Relationships**
18
- **Complete business relationship management!** Demonstrates advanced caching patterns with entity relationships:
19
- - **Multiple interconnected models**: Customer, Order, Product, SupportTicket
20
- - **Automatic reference population**: Orders automatically include customer data
21
- - **Required vs optional aggregates**: Flexible relationship management
22
- - **Complex business scenarios**: E-commerce platform with customer management
23
- - **Performance optimization**: Cache efficiency through aggregated data
24
-
25
- Shows how fjell-cache handles enterprise data relationship patterns.
26
-
27
- ### 3. `cache-map-example.ts` 🔧 **Low-Level Cache Operations**
28
- **Direct cache management!** Demonstrates lower-level CacheMap functionality:
29
- - **Direct CacheMap usage**: Create and manage cache maps without higher-level abstractions
30
- - **Primary and composite keys**: Handle both simple and complex key structures
31
- - **Location-based operations**: Filter contained items by location hierarchy
32
- - **Performance characteristics**: Bulk operations and efficiency testing
33
- - **Cache lifecycle**: Cloning, cleanup, and memory management
34
-
35
- Perfect for understanding the underlying cache mechanisms and advanced use cases.
36
-
37
- ## Key Concepts Demonstrated
38
-
39
- ### Basic Caching Operations (basic-cache-example.ts)
40
- ```typescript
41
- // Import fjell-cache functionality
42
- import { createCache } from '@fjell/cache';
43
- import { createCoordinate, createRegistry } from '@fjell/registry';
44
- import { ClientApi } from '@fjell/client-api';
45
-
46
- // Create a registry for cache management
47
- const registry = createRegistry();
48
-
49
- // Create a cache instance with API integration
50
- const userApi = createUserApi(); // Your API implementation
51
- const userCache = await createCache(userApi, createCoordinate('user'), registry);
52
-
53
- // Cache is now an instance - no need for separate createInstance call
54
- // Perform cache operations through the operations API
55
- const [cacheMap, allUsers] = await userCache.operations.all();
56
- const [, cachedUser] = await userCache.operations.get(userKey);
57
- const [, retrievedUser] = await userCache.operations.retrieve(userKey); // Cache hit!
58
-
59
- await userCache.operations.set(userKey, updatedUser);
60
- ```
61
-
62
- ### Advanced Aggregation (aggregator-example.ts)
63
- ```typescript
64
- // Create aggregated cache with relationships
65
- const orderAggregator = await createAggregator(orderCache, {
66
- aggregates: {
67
- customer: { cache: customerCache, optional: false }, // Required reference
68
- product: { cache: productCache, optional: true }, // Optional reference
69
- },
70
- events: {}
71
- });
72
-
73
- // Automatically populate related entities
74
- const populatedOrder = await orderAggregator.populate(order);
75
- if (populatedOrder.aggs?.customer?.item) {
76
- const customer = populatedOrder.aggs.customer.item;
77
- console.log(`Order for: ${customer.name} (${customer.email})`);
78
- }
79
-
80
- // Aggregator is now itself an instance - access operations directly
81
- const [, orders] = await orderAggregator.all();
82
- ```
83
-
84
- ### Direct Cache Management (cache-map-example.ts)
85
- ```typescript
86
- // Create CacheMap instances directly
87
- const documentCacheMap = new CacheMap<Document, 'document'>(['document']);
88
- const commentCacheMap = new CacheMap<Comment, 'comment', 'document'>(['comment', 'document']);
89
-
90
- // Basic operations
91
- documentCacheMap.set(documentKey, document);
92
- const retrievedDoc = documentCacheMap.get(documentKey);
93
- const hasDoc = documentCacheMap.includesKey(documentKey);
94
-
95
- // Bulk operations
96
- const allDocuments = documentCacheMap.allIn([]);
97
- const allKeys = documentCacheMap.keys();
98
- const allValues = documentCacheMap.values();
99
-
100
- // Location-based filtering for contained items
101
- const commentsInDoc = commentCacheMap.allIn([{ kt: 'document', lk: documentId }]);
102
-
103
- // Performance operations
104
- const clonedCache = documentCacheMap.clone();
105
- documentCacheMap.delete(documentKey);
106
- ```
107
-
108
- ### Data Model Patterns
109
-
110
- #### Primary Items
111
- - Standalone entities (User, Customer, Document)
112
- - No location hierarchy constraints
113
- - Simple key structure: `Item<'keyType'>`
114
-
115
- #### Contained Items
116
- - Nested within other entities or locations
117
- - Multi-level location keys for organization
118
- - Complex key structure: `Item<'keyType', 'location1', 'location2', ...>`
119
-
120
- #### Aggregated Items
121
- - Items with automatic reference population
122
- - Business relationships through cache aggregation
123
- - Performance optimized through cached references
124
-
125
- ## Running Examples
126
-
127
- ```bash
128
- # Start with the basic example (recommended)
129
- npx tsx examples/basic-cache-example.ts
130
-
131
- # Run the aggregator example
132
- npx tsx examples/aggregator-example.ts
133
-
134
- # Run the cache map example
135
- npx tsx examples/cache-map-example.ts
136
-
137
- # Or with Node.js
138
- node -r esbuild-register examples/basic-cache-example.ts
139
- ```
140
-
141
- ## Integration with Real Applications
142
-
143
- All examples use the actual fjell-cache functionality! In production applications:
144
-
145
- ```typescript
146
- import { createCache, createRegistry, createInstance, createAggregator } from '@fjell/cache';
147
- import { ClientApi } from '@fjell/client-api';
148
-
149
- // Basic cache setup
150
- const registry = createRegistry();
151
-
152
- const userCache = await createCache(userApi, 'user');
153
- const userInstance = createInstance(registry, createCoordinate('user'), userCache);
154
-
155
- // With aggregation for business relationships
156
- const orderAggregator = await createAggregator(orderCache, {
157
- aggregates: {
158
- customer: { cache: customerCache, optional: false },
159
- items: { cache: productCache, optional: true }
160
- },
161
- events: {
162
- orderUpdated: async (key, item) => {
163
- // Custom event handling
164
- await notifyCustomer(item);
165
- }
166
- }
167
- });
168
-
169
- // Advanced cache configuration
170
- const options = {
171
- cacheSize: 10000,
172
- ttl: 3600000, // 1 hour
173
- refreshThreshold: 0.8,
174
- compression: true
175
- };
176
- ```
177
-
178
- ## Cache Operation Types
179
-
180
- ### Basic Operations
181
- - **all()**: Get all items and update cache
182
- - **get()**: Get item by key, fetch from API if not cached
183
- - **retrieve()**: Get item by key, return null if not cached
184
- - **set()**: Store item in cache
185
- - **one()**: Get single item
186
- - **find()**: Search items with finder methods
187
-
188
- ### Aggregation Operations
189
- - **populate()**: Automatically populate item with related entities
190
- - **populateAggregate()**: Populate specific aggregate relationship
191
- - **populateEvent()**: Handle population events
192
-
193
- ### Cache Management
194
- - **allIn()**: Get items by location (for contained items)
195
- - **queryIn()**: Query items by location with filtering
196
- - **clone()**: Create independent cache copy
197
- - **delete()**: Remove item from cache
198
- - **clear()**: Clear all cache contents
199
-
200
- ### Business Operations
201
- ```typescript
202
- // Cache with business logic integration
203
- const cache = await createCache(api, 'order', {
204
- hooks: {
205
- beforeGet: async (key) => { /* validation */ },
206
- afterSet: async (key, item) => { /* notifications */ }
207
- },
208
- validators: {
209
- status: (status) => ['pending', 'shipped', 'delivered'].includes(status)
210
- },
211
- aggregates: {
212
- customer: customerCache,
213
- items: productCache
214
- }
215
- });
216
- ```
217
-
218
- ## When to Use What
219
-
220
- **Use `basic-cache-example.ts` approach when:**
221
- - Learning fjell-cache fundamentals
222
- - Building simple applications with caching needs
223
- - Need basic get/set cache operations
224
- - Working with independent data models
225
-
226
- **Use `aggregator-example.ts` approach when:**
227
- - Managing complex business relationships
228
- - Need automatic population of related entities
229
- - Building enterprise applications with interconnected data
230
- - Require performance optimization through aggregated caching
231
- - Working with customer/order/product type relationships
232
-
233
- **Use `cache-map-example.ts` approach when:**
234
- - Need direct control over cache operations
235
- - Building custom caching solutions
236
- - Working with contained items and location hierarchies
237
- - Require maximum performance and minimal overhead
238
- - Implementing cache-based data structures
239
-
240
- ## Advanced Features
241
-
242
- ### Cache Aggregation
243
- ```typescript
244
- // Complex aggregation with optional and required references
245
- const ticketAggregator = await createAggregator(ticketCache, {
246
- aggregates: {
247
- customer: { cache: customerCache, optional: false }, // Always populated
248
- order: { cache: orderCache, optional: true }, // Only if orderId exists
249
- assignee: { cache: userCache, optional: true } // Only if assigned
250
- },
251
- events: {
252
- ticketAssigned: async (key, ticket) => {
253
- await notifyAssignee(ticket);
254
- }
255
- }
256
- });
257
-
258
- // Automatic population includes all available references
259
- const populatedTicket = await ticketAggregator.populate(ticket);
260
- ```
261
-
262
- ### Performance Optimization
263
- ```typescript
264
- // Cache with coordinate and registry
265
- const cache = await createCache(api, createCoordinate('product'), registry);
266
-
267
- // Bulk operations for efficiency
268
- const [cacheMap, allProducts] = await cache.operations.all();
269
- const productMap = new Map(allProducts.map(p => [p.id, p]));
270
-
271
- // Access cache properties for optimization
272
- console.log(`Cache coordinate: ${cache.coordinate.kta.join(', ')}`);
273
- console.log(`Cached items: ${cache.cacheMap.size()}`);
274
- ```
275
-
276
- ### Storage Integration
277
- Fjell-cache works with any storage backend through the ClientApi interface:
278
- - SQL databases (PostgreSQL, MySQL, SQLite)
279
- - NoSQL databases (MongoDB, DynamoDB, Redis)
280
- - REST APIs and GraphQL endpoints
281
- - In-memory stores and mock data
282
- - File systems and cloud storage
283
- - Custom data sources
284
-
285
- ### Error Handling and Resilience
286
- ```typescript
287
- // Cache with proper error handling through the API layer
288
- const resilientCache = await createCache(api, createCoordinate('user'), registry);
289
-
290
- // Error handling in operations
291
- try {
292
- const [, user] = await resilientCache.operations.get(userKey);
293
- return user;
294
- } catch (error) {
295
- // Handle cache errors gracefully
296
- console.error('Cache operation failed:', error);
297
- // Fallback to direct API call
298
- return await api.get(userKey);
299
- }
300
- ```
301
-
302
- This provides the foundation for building scalable, maintainable applications with intelligent caching using fjell-cache.
File without changes
@@ -1,3 +0,0 @@
1
- /* Custom styles for fjell-cache docs */
2
-
3
- /* Additional styles can be added here to customize the cache theme */
package/docs/src/main.tsx DELETED
@@ -1,12 +0,0 @@
1
- import React from 'react'
2
- import ReactDOM from 'react-dom/client'
3
- import { DocsApp } from '@fjell/docs-template'
4
- import '@fjell/docs-template/dist/index.css'
5
- import config from '../docs.config'
6
- import './index.css'
7
-
8
- ReactDOM.createRoot(document.getElementById('root')!).render(
9
- <React.StrictMode>
10
- <DocsApp config={config} />
11
- </React.StrictMode>
12
- )
@@ -1 +0,0 @@
1
- import '@testing-library/jest-dom'
@@ -1,15 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "composite": true,
4
- "skipLibCheck": true,
5
- "module": "ESNext",
6
- "moduleResolution": "bundler",
7
- "allowSyntheticDefaultImports": true,
8
- "strict": true,
9
- "noEmit": true
10
- },
11
- "include": [
12
- "vite.config.ts",
13
- "docs.config.ts"
14
- ]
15
- }
@@ -1,302 +0,0 @@
1
- # Fjell-Cache Examples
2
-
3
- This directory contains examples demonstrating how to use fjell-cache for caching data models and managing complex business relationships with different patterns and complexity levels.
4
-
5
- ## Examples
6
-
7
- ### 1. `basic-cache-example.ts` ⭐ **Start Here!**
8
- **Perfect for beginners!** Demonstrates the fundamental way to use fjell-cache for data caching:
9
- - **Basic cache operations** - Create caches with coordinates and registries, use operations API
10
- - **Simple data models** - User and Task entities with mock storage
11
- - **Cache-as-Instance architecture** - Caches extend Instance from fjell-registry
12
- - **Cache hits vs misses** - Understand cache behavior and performance benefits
13
- - **Cache management** - Updates, deletions, and data consistency through operations
14
-
15
- Great for understanding the fundamentals of fjell-cache data management.
16
-
17
- ### 2. `aggregator-example.ts` 🏗️ **Advanced Business Relationships**
18
- **Complete business relationship management!** Demonstrates advanced caching patterns with entity relationships:
19
- - **Multiple interconnected models**: Customer, Order, Product, SupportTicket
20
- - **Automatic reference population**: Orders automatically include customer data
21
- - **Required vs optional aggregates**: Flexible relationship management
22
- - **Complex business scenarios**: E-commerce platform with customer management
23
- - **Performance optimization**: Cache efficiency through aggregated data
24
-
25
- Shows how fjell-cache handles enterprise data relationship patterns.
26
-
27
- ### 3. `cache-map-example.ts` 🔧 **Low-Level Cache Operations**
28
- **Direct cache management!** Demonstrates lower-level CacheMap functionality:
29
- - **Direct CacheMap usage**: Create and manage cache maps without higher-level abstractions
30
- - **Primary and composite keys**: Handle both simple and complex key structures
31
- - **Location-based operations**: Filter contained items by location hierarchy
32
- - **Performance characteristics**: Bulk operations and efficiency testing
33
- - **Cache lifecycle**: Cloning, cleanup, and memory management
34
-
35
- Perfect for understanding the underlying cache mechanisms and advanced use cases.
36
-
37
- ## Key Concepts Demonstrated
38
-
39
- ### Basic Caching Operations (basic-cache-example.ts)
40
- ```typescript
41
- // Import fjell-cache functionality
42
- import { createCache } from '@fjell/cache';
43
- import { createCoordinate, createRegistry } from '@fjell/registry';
44
- import { ClientApi } from '@fjell/client-api';
45
-
46
- // Create a registry for cache management
47
- const registry = createRegistry();
48
-
49
- // Create a cache instance with API integration
50
- const userApi = createUserApi(); // Your API implementation
51
- const userCache = await createCache(userApi, createCoordinate('user'), registry);
52
-
53
- // Cache is now an instance - no need for separate createInstance call
54
- // Perform cache operations through the operations API
55
- const [cacheMap, allUsers] = await userCache.operations.all();
56
- const [, cachedUser] = await userCache.operations.get(userKey);
57
- const [, retrievedUser] = await userCache.operations.retrieve(userKey); // Cache hit!
58
-
59
- await userCache.operations.set(userKey, updatedUser);
60
- ```
61
-
62
- ### Advanced Aggregation (aggregator-example.ts)
63
- ```typescript
64
- // Create aggregated cache with relationships
65
- const orderAggregator = await createAggregator(orderCache, {
66
- aggregates: {
67
- customer: { cache: customerCache, optional: false }, // Required reference
68
- product: { cache: productCache, optional: true }, // Optional reference
69
- },
70
- events: {}
71
- });
72
-
73
- // Automatically populate related entities
74
- const populatedOrder = await orderAggregator.populate(order);
75
- if (populatedOrder.aggs?.customer?.item) {
76
- const customer = populatedOrder.aggs.customer.item;
77
- console.log(`Order for: ${customer.name} (${customer.email})`);
78
- }
79
-
80
- // Aggregator is now itself an instance - access operations directly
81
- const [, orders] = await orderAggregator.all();
82
- ```
83
-
84
- ### Direct Cache Management (cache-map-example.ts)
85
- ```typescript
86
- // Create CacheMap instances directly
87
- const documentCacheMap = new CacheMap<Document, 'document'>(['document']);
88
- const commentCacheMap = new CacheMap<Comment, 'comment', 'document'>(['comment', 'document']);
89
-
90
- // Basic operations
91
- documentCacheMap.set(documentKey, document);
92
- const retrievedDoc = documentCacheMap.get(documentKey);
93
- const hasDoc = documentCacheMap.includesKey(documentKey);
94
-
95
- // Bulk operations
96
- const allDocuments = documentCacheMap.allIn([]);
97
- const allKeys = documentCacheMap.keys();
98
- const allValues = documentCacheMap.values();
99
-
100
- // Location-based filtering for contained items
101
- const commentsInDoc = commentCacheMap.allIn([{ kt: 'document', lk: documentId }]);
102
-
103
- // Performance operations
104
- const clonedCache = documentCacheMap.clone();
105
- documentCacheMap.delete(documentKey);
106
- ```
107
-
108
- ### Data Model Patterns
109
-
110
- #### Primary Items
111
- - Standalone entities (User, Customer, Document)
112
- - No location hierarchy constraints
113
- - Simple key structure: `Item<'keyType'>`
114
-
115
- #### Contained Items
116
- - Nested within other entities or locations
117
- - Multi-level location keys for organization
118
- - Complex key structure: `Item<'keyType', 'location1', 'location2', ...>`
119
-
120
- #### Aggregated Items
121
- - Items with automatic reference population
122
- - Business relationships through cache aggregation
123
- - Performance optimized through cached references
124
-
125
- ## Running Examples
126
-
127
- ```bash
128
- # Start with the basic example (recommended)
129
- npx tsx examples/basic-cache-example.ts
130
-
131
- # Run the aggregator example
132
- npx tsx examples/aggregator-example.ts
133
-
134
- # Run the cache map example
135
- npx tsx examples/cache-map-example.ts
136
-
137
- # Or with Node.js
138
- node -r esbuild-register examples/basic-cache-example.ts
139
- ```
140
-
141
- ## Integration with Real Applications
142
-
143
- All examples use the actual fjell-cache functionality! In production applications:
144
-
145
- ```typescript
146
- import { createCache, createRegistry, createInstance, createAggregator } from '@fjell/cache';
147
- import { ClientApi } from '@fjell/client-api';
148
-
149
- // Basic cache setup
150
- const registry = createRegistry();
151
-
152
- const userCache = await createCache(userApi, 'user');
153
- const userInstance = createInstance(registry, createCoordinate('user'), userCache);
154
-
155
- // With aggregation for business relationships
156
- const orderAggregator = await createAggregator(orderCache, {
157
- aggregates: {
158
- customer: { cache: customerCache, optional: false },
159
- items: { cache: productCache, optional: true }
160
- },
161
- events: {
162
- orderUpdated: async (key, item) => {
163
- // Custom event handling
164
- await notifyCustomer(item);
165
- }
166
- }
167
- });
168
-
169
- // Advanced cache configuration
170
- const options = {
171
- cacheSize: 10000,
172
- ttl: 3600000, // 1 hour
173
- refreshThreshold: 0.8,
174
- compression: true
175
- };
176
- ```
177
-
178
- ## Cache Operation Types
179
-
180
- ### Basic Operations
181
- - **all()**: Get all items and update cache
182
- - **get()**: Get item by key, fetch from API if not cached
183
- - **retrieve()**: Get item by key, return null if not cached
184
- - **set()**: Store item in cache
185
- - **one()**: Get single item
186
- - **find()**: Search items with finder methods
187
-
188
- ### Aggregation Operations
189
- - **populate()**: Automatically populate item with related entities
190
- - **populateAggregate()**: Populate specific aggregate relationship
191
- - **populateEvent()**: Handle population events
192
-
193
- ### Cache Management
194
- - **allIn()**: Get items by location (for contained items)
195
- - **queryIn()**: Query items by location with filtering
196
- - **clone()**: Create independent cache copy
197
- - **delete()**: Remove item from cache
198
- - **clear()**: Clear all cache contents
199
-
200
- ### Business Operations
201
- ```typescript
202
- // Cache with business logic integration
203
- const cache = await createCache(api, 'order', {
204
- hooks: {
205
- beforeGet: async (key) => { /* validation */ },
206
- afterSet: async (key, item) => { /* notifications */ }
207
- },
208
- validators: {
209
- status: (status) => ['pending', 'shipped', 'delivered'].includes(status)
210
- },
211
- aggregates: {
212
- customer: customerCache,
213
- items: productCache
214
- }
215
- });
216
- ```
217
-
218
- ## When to Use What
219
-
220
- **Use `basic-cache-example.ts` approach when:**
221
- - Learning fjell-cache fundamentals
222
- - Building simple applications with caching needs
223
- - Need basic get/set cache operations
224
- - Working with independent data models
225
-
226
- **Use `aggregator-example.ts` approach when:**
227
- - Managing complex business relationships
228
- - Need automatic population of related entities
229
- - Building enterprise applications with interconnected data
230
- - Require performance optimization through aggregated caching
231
- - Working with customer/order/product type relationships
232
-
233
- **Use `cache-map-example.ts` approach when:**
234
- - Need direct control over cache operations
235
- - Building custom caching solutions
236
- - Working with contained items and location hierarchies
237
- - Require maximum performance and minimal overhead
238
- - Implementing cache-based data structures
239
-
240
- ## Advanced Features
241
-
242
- ### Cache Aggregation
243
- ```typescript
244
- // Complex aggregation with optional and required references
245
- const ticketAggregator = await createAggregator(ticketCache, {
246
- aggregates: {
247
- customer: { cache: customerCache, optional: false }, // Always populated
248
- order: { cache: orderCache, optional: true }, // Only if orderId exists
249
- assignee: { cache: userCache, optional: true } // Only if assigned
250
- },
251
- events: {
252
- ticketAssigned: async (key, ticket) => {
253
- await notifyAssignee(ticket);
254
- }
255
- }
256
- });
257
-
258
- // Automatic population includes all available references
259
- const populatedTicket = await ticketAggregator.populate(ticket);
260
- ```
261
-
262
- ### Performance Optimization
263
- ```typescript
264
- // Cache with coordinate and registry
265
- const cache = await createCache(api, createCoordinate('product'), registry);
266
-
267
- // Bulk operations for efficiency
268
- const [cacheMap, allProducts] = await cache.operations.all();
269
- const productMap = new Map(allProducts.map(p => [p.id, p]));
270
-
271
- // Access cache properties for optimization
272
- console.log(`Cache coordinate: ${cache.coordinate.kta.join(', ')}`);
273
- console.log(`Cached items: ${cache.cacheMap.size()}`);
274
- ```
275
-
276
- ### Storage Integration
277
- Fjell-cache works with any storage backend through the ClientApi interface:
278
- - SQL databases (PostgreSQL, MySQL, SQLite)
279
- - NoSQL databases (MongoDB, DynamoDB, Redis)
280
- - REST APIs and GraphQL endpoints
281
- - In-memory stores and mock data
282
- - File systems and cloud storage
283
- - Custom data sources
284
-
285
- ### Error Handling and Resilience
286
- ```typescript
287
- // Cache with proper error handling through the API layer
288
- const resilientCache = await createCache(api, createCoordinate('user'), registry);
289
-
290
- // Error handling in operations
291
- try {
292
- const [, user] = await resilientCache.operations.get(userKey);
293
- return user;
294
- } catch (error) {
295
- // Handle cache errors gracefully
296
- console.error('Cache operation failed:', error);
297
- // Fallback to direct API call
298
- return await api.get(userKey);
299
- }
300
- ```
301
-
302
- This provides the foundation for building scalable, maintainable applications with intelligent caching using fjell-cache.