@fjell/client-api 4.4.6 → 4.4.9
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.
- package/dist/Instance.d.ts +19 -0
- package/dist/Instance.js +19 -0
- package/dist/Instance.js.map +1 -0
- package/dist/InstanceFactory.d.ts +8 -0
- package/dist/InstanceFactory.js +19 -0
- package/dist/InstanceFactory.js.map +1 -0
- package/dist/Registry.d.ts +15 -0
- package/dist/Registry.js +31 -0
- package/dist/Registry.js.map +1 -0
- package/dist/index.cjs +106 -47
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/examples/README.md +387 -0
- package/examples/enterprise-example.ts +852 -0
- package/examples/multi-level-keys.ts +467 -0
- package/examples/simple-example.ts +346 -0
- package/package.json +4 -3
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
# Fjell-Client-API Examples
|
|
2
|
+
|
|
3
|
+
This directory contains examples demonstrating how to use fjell-client-api for HTTP-based data operations and client-side API management with different patterns and complexity levels.
|
|
4
|
+
|
|
5
|
+
## Examples
|
|
6
|
+
|
|
7
|
+
### 1. `simple-example.ts` ⭐ **Start Here!**
|
|
8
|
+
**Perfect for beginners!** Demonstrates the simplest way to use fjell-client-api for HTTP data operations:
|
|
9
|
+
- **Basic CRUD operations** - Create, Read, Update, Delete through HTTP endpoints
|
|
10
|
+
- **Primary and Contained APIs** - PItemApi for independent entities, CItemApi for hierarchical data
|
|
11
|
+
- **Client API configuration** - HTTP endpoints, authentication, and error handling
|
|
12
|
+
- **Actions and facets** - Business logic execution and analytics retrieval
|
|
13
|
+
|
|
14
|
+
Great for understanding the fundamentals of fjell-client-api HTTP operations.
|
|
15
|
+
|
|
16
|
+
### 2. `multi-level-keys.ts`
|
|
17
|
+
**Advanced hierarchical data models!** Demonstrates complex data structures with multi-level contained items:
|
|
18
|
+
- **Hierarchical models**: Organization → Department → Employee
|
|
19
|
+
- **Multi-level location keys**: Complex organizational structure management
|
|
20
|
+
- **Nested API routing**: `/organizations/{orgId}/departments/{deptId}/employees/{empId}`
|
|
21
|
+
- **Cross-hierarchy operations**: Complex queries spanning multiple organizational levels
|
|
22
|
+
- **Location-based analytics**: Department and employee-specific metrics and operations
|
|
23
|
+
|
|
24
|
+
Shows how fjell-client-api handles enterprise organizational data patterns with deep hierarchies.
|
|
25
|
+
|
|
26
|
+
### 3. `enterprise-example.ts` 🏗️ **Full Business Application**
|
|
27
|
+
**Complete enterprise e-commerce system!** Demonstrates advanced business application patterns:
|
|
28
|
+
- **Multiple interconnected entities**: Customer, Product, Order, OrderItem, SupportTicket, ProductReview
|
|
29
|
+
- **Business workflow automation**: Order fulfillment, support ticket resolution, inventory management
|
|
30
|
+
- **Advanced analytics facets**: Customer analytics, product performance, order metrics
|
|
31
|
+
- **Enterprise features**: Multi-tenant configuration, complex business logic, predictive analytics
|
|
32
|
+
- **Real business scenarios**: Complete e-commerce platform with customer lifecycle management
|
|
33
|
+
|
|
34
|
+
Perfect for understanding how to build complete enterprise applications with fjell-client-api.
|
|
35
|
+
|
|
36
|
+
## Key Concepts Demonstrated
|
|
37
|
+
|
|
38
|
+
### Basic Client API Operations (simple-example.ts)
|
|
39
|
+
```typescript
|
|
40
|
+
// Import fjell-client-api functionality
|
|
41
|
+
import { createPItemApi, createCItemApi } from '@fjell/client-api';
|
|
42
|
+
|
|
43
|
+
// Configure API endpoints
|
|
44
|
+
const apiConfig = {
|
|
45
|
+
baseUrl: 'http://localhost:3000/api',
|
|
46
|
+
headers: { 'Authorization': 'Bearer token' }
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
// Create Primary Item API (independent entities)
|
|
50
|
+
const userApi = createPItemApi<User, 'user'>('user', ['users'], apiConfig);
|
|
51
|
+
|
|
52
|
+
// Create Contained Item API (hierarchical entities)
|
|
53
|
+
const taskApi = createCItemApi<Task, 'task', 'user'>('task', ['users', 'tasks'], apiConfig);
|
|
54
|
+
|
|
55
|
+
// Basic operations
|
|
56
|
+
const users = await userApi.all(query);
|
|
57
|
+
const user = await userApi.create(userData);
|
|
58
|
+
const tasks = await taskApi.all(query, [userId]); // Location-based query
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Hierarchical Data Management (multi-level-keys.ts)
|
|
62
|
+
```typescript
|
|
63
|
+
// Multi-level organizational structure
|
|
64
|
+
// Organization (Level 0) → Department (Level 1) → Employee (Level 2)
|
|
65
|
+
|
|
66
|
+
// Organization API (Primary Items)
|
|
67
|
+
const orgApi = createPItemApi<Organization, 'organization'>('organization', ['organizations'], config);
|
|
68
|
+
|
|
69
|
+
// Department API (Contained in Organization)
|
|
70
|
+
const deptApi = createCItemApi<Department, 'department', 'organization'>(
|
|
71
|
+
'department',
|
|
72
|
+
['organizations', 'departments'],
|
|
73
|
+
config
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
// Employee API (Contained in Department within Organization)
|
|
77
|
+
const empApi = createCItemApi<Employee, 'employee', 'organization', 'department'>(
|
|
78
|
+
'employee',
|
|
79
|
+
['organizations', 'departments', 'employees'],
|
|
80
|
+
config
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
// Multi-level operations
|
|
84
|
+
const orgLocation = [organizationId];
|
|
85
|
+
const deptLocation = [organizationId, departmentId];
|
|
86
|
+
|
|
87
|
+
await deptApi.all(query, orgLocation); // All departments in org
|
|
88
|
+
await empApi.all(query, deptLocation); // All employees in dept
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### Enterprise Business Workflows (enterprise-example.ts)
|
|
92
|
+
```typescript
|
|
93
|
+
// Customer lifecycle management
|
|
94
|
+
const customerApi = createPItemApi<Customer, 'customer'>('customer', ['customers'], config);
|
|
95
|
+
const supportApi = createCItemApi<SupportTicket, 'supportTicket', 'customer'>(
|
|
96
|
+
'supportTicket',
|
|
97
|
+
['customers', 'tickets'],
|
|
98
|
+
config
|
|
99
|
+
);
|
|
100
|
+
|
|
101
|
+
// Business workflow example
|
|
102
|
+
// 1. Create customer
|
|
103
|
+
const customer = await customerApi.create(customerData);
|
|
104
|
+
|
|
105
|
+
// 2. Create support ticket for customer
|
|
106
|
+
const ticket = await supportApi.create(ticketData, [customer.id]);
|
|
107
|
+
|
|
108
|
+
// 3. Execute business actions
|
|
109
|
+
await supportApi.action(ticketKey, 'escalate-ticket', { reason: 'complex issue' });
|
|
110
|
+
await supportApi.action(ticketKey, 'resolve-ticket', { resolution: 'provided solution' });
|
|
111
|
+
|
|
112
|
+
// 4. Get business analytics
|
|
113
|
+
const customerMetrics = await customerApi.facet(customerKey, 'loyalty-metrics');
|
|
114
|
+
const supportAnalytics = await supportApi.allFacet('resolution-metrics', {}, [customer.id]);
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## API Types and Patterns
|
|
118
|
+
|
|
119
|
+
### Primary Item API (PItemApi)
|
|
120
|
+
Used for independent entities that exist at the top level:
|
|
121
|
+
- **Endpoints**: `/entities/{id}`
|
|
122
|
+
- **Use cases**: Customers, Products, Orders, Organizations
|
|
123
|
+
- **Operations**: Standard CRUD + actions + facets
|
|
124
|
+
- **No location context required**
|
|
125
|
+
|
|
126
|
+
```typescript
|
|
127
|
+
interface PItemApi<V, S> {
|
|
128
|
+
all(query: ItemQuery): Promise<V[]>;
|
|
129
|
+
create(item: Partial<Item<S>>): Promise<V>;
|
|
130
|
+
get(key: PriKey<S>): Promise<V>;
|
|
131
|
+
update(key: PriKey<S>, updates: Partial<Item<S>>): Promise<V>;
|
|
132
|
+
remove(key: PriKey<S>): Promise<boolean>;
|
|
133
|
+
action(key: PriKey<S>, action: string, body?: any): Promise<any>;
|
|
134
|
+
find(finder: string, params?: any): Promise<V[]>;
|
|
135
|
+
facet(key: PriKey<S>, facet: string, params?: any): Promise<any>;
|
|
136
|
+
allAction(action: string, body?: any): Promise<V[]>;
|
|
137
|
+
allFacet(facet: string, params?: any): Promise<any>;
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Contained Item API (CItemApi)
|
|
142
|
+
Used for hierarchical entities that belong to parent locations:
|
|
143
|
+
- **Endpoints**: `/parents/{parentId}/entities/{id}`
|
|
144
|
+
- **Use cases**: Tasks (in Users), OrderItems (in Orders), Employees (in Departments)
|
|
145
|
+
- **Operations**: CRUD + actions + facets with location context
|
|
146
|
+
- **Requires location arrays for context**
|
|
147
|
+
|
|
148
|
+
```typescript
|
|
149
|
+
interface CItemApi<V, S, L1, L2, L3, L4, L5> extends ClientApi<V, S, L1, L2, L3, L4, L5> {
|
|
150
|
+
all(query: ItemQuery, locations?: LocKeyArray<L1, L2, L3, L4, L5>): Promise<V[]>;
|
|
151
|
+
create(item: Partial<Item<S>>, locations?: LocKeyArray<L1, L2, L3, L4, L5>): Promise<V>;
|
|
152
|
+
find(finder: string, params?: any, locations?: LocKeyArray<L1, L2, L3, L4, L5>): Promise<V[]>;
|
|
153
|
+
allAction(action: string, body?: any, locations?: LocKeyArray<L1, L2, L3, L4, L5>): Promise<V[]>;
|
|
154
|
+
allFacet(facet: string, params?: any, locations?: LocKeyArray<L1, L2, L3, L4, L5>): Promise<any>;
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Business Logic Patterns
|
|
159
|
+
|
|
160
|
+
### Actions - Business Logic Execution
|
|
161
|
+
Actions execute business logic on entities or collections:
|
|
162
|
+
|
|
163
|
+
```typescript
|
|
164
|
+
// Single entity actions
|
|
165
|
+
await userApi.action(userKey, 'activate', { reason: 'manual activation' });
|
|
166
|
+
await orderApi.action(orderKey, 'fulfill-order', { warehouse: 'main' });
|
|
167
|
+
await ticketApi.action(ticketKey, 'escalate', { priority: 'urgent' });
|
|
168
|
+
|
|
169
|
+
// Batch actions on collections
|
|
170
|
+
await userApi.allAction('updatePreferences', { newsletter: true });
|
|
171
|
+
await productApi.allAction('applyDiscount', { percent: 10 });
|
|
172
|
+
await orderApi.allAction('expediteShipping', { method: 'express' });
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Facets - Analytics and Data Retrieval
|
|
176
|
+
Facets retrieve analytics, computed data, and business insights:
|
|
177
|
+
|
|
178
|
+
```typescript
|
|
179
|
+
// Entity-specific analytics
|
|
180
|
+
const userStats = await userApi.facet(userKey, 'purchase-history');
|
|
181
|
+
const productMetrics = await productApi.facet(productKey, 'performance-metrics');
|
|
182
|
+
const orderStatus = await orderApi.facet(orderKey, 'fulfillment-status');
|
|
183
|
+
|
|
184
|
+
// Aggregated analytics
|
|
185
|
+
const customerAnalytics = await customerApi.allFacet('revenue-analytics', { period: 'quarterly' });
|
|
186
|
+
const inventoryReport = await productApi.allFacet('inventory-analytics', { lowStock: true });
|
|
187
|
+
const salesMetrics = await orderApi.allFacet('sales-metrics', { region: 'north-america' });
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## Configuration Patterns
|
|
191
|
+
|
|
192
|
+
### Basic Configuration
|
|
193
|
+
```typescript
|
|
194
|
+
const apiConfig = {
|
|
195
|
+
baseUrl: 'https://api.example.com',
|
|
196
|
+
headers: {
|
|
197
|
+
'Content-Type': 'application/json',
|
|
198
|
+
'Authorization': 'Bearer your-api-token'
|
|
199
|
+
},
|
|
200
|
+
timeout: 5000
|
|
201
|
+
};
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
### Enterprise Configuration
|
|
205
|
+
```typescript
|
|
206
|
+
const enterpriseConfig = {
|
|
207
|
+
baseUrl: 'https://api.enterprise.com/v1',
|
|
208
|
+
headers: {
|
|
209
|
+
'Content-Type': 'application/json',
|
|
210
|
+
'Authorization': 'Bearer enterprise-token',
|
|
211
|
+
'X-Tenant-ID': 'tenant-001',
|
|
212
|
+
'X-Environment': 'production'
|
|
213
|
+
},
|
|
214
|
+
timeout: 10000,
|
|
215
|
+
retries: 3,
|
|
216
|
+
readAuthenticated: true,
|
|
217
|
+
writeAuthenticated: true
|
|
218
|
+
};
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
## Error Handling Patterns
|
|
222
|
+
|
|
223
|
+
### Basic Error Handling
|
|
224
|
+
```typescript
|
|
225
|
+
try {
|
|
226
|
+
const user = await userApi.get(userKey);
|
|
227
|
+
if (!user) {
|
|
228
|
+
console.log('User not found');
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
// Process user...
|
|
232
|
+
} catch (error) {
|
|
233
|
+
console.error('API error:', error);
|
|
234
|
+
// Handle specific error types
|
|
235
|
+
if (error.status === 404) {
|
|
236
|
+
// Handle not found
|
|
237
|
+
} else if (error.status === 401) {
|
|
238
|
+
// Handle authentication error
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
### Enterprise Error Handling
|
|
244
|
+
```typescript
|
|
245
|
+
try {
|
|
246
|
+
const result = await customerApi.action(customerKey, 'process-order', orderData);
|
|
247
|
+
return result;
|
|
248
|
+
} catch (error) {
|
|
249
|
+
// Log error with context
|
|
250
|
+
console.error('Order processing failed:', {
|
|
251
|
+
customerId: customerKey.id,
|
|
252
|
+
error: error.message,
|
|
253
|
+
timestamp: new Date()
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
// Implement retry logic for transient errors
|
|
257
|
+
if (error.isRetryable) {
|
|
258
|
+
return await retryOperation(() =>
|
|
259
|
+
customerApi.action(customerKey, 'process-order', orderData)
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
throw error;
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
## Testing Patterns
|
|
268
|
+
|
|
269
|
+
The examples include comprehensive integration tests in `tests/examples/` that demonstrate:
|
|
270
|
+
|
|
271
|
+
- **API operation testing** - Verifying CRUD operations work correctly
|
|
272
|
+
- **Business workflow testing** - Testing complete business processes
|
|
273
|
+
- **Error scenario testing** - Handling various error conditions
|
|
274
|
+
- **Performance testing** - Measuring API response times
|
|
275
|
+
- **Mock API testing** - Testing with mock backend services
|
|
276
|
+
|
|
277
|
+
### Running Tests
|
|
278
|
+
```bash
|
|
279
|
+
# Run all example tests
|
|
280
|
+
npm test -- tests/examples
|
|
281
|
+
|
|
282
|
+
# Run specific example tests
|
|
283
|
+
npm test -- tests/examples/simple-example.integration.test.ts
|
|
284
|
+
npm test -- tests/examples/multi-level-keys.integration.test.ts
|
|
285
|
+
npm test -- tests/examples/enterprise-example.integration.test.ts
|
|
286
|
+
|
|
287
|
+
# Run with coverage
|
|
288
|
+
npm run test:coverage -- tests/examples
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
## Real-World Usage
|
|
292
|
+
|
|
293
|
+
### When to Use PItemApi
|
|
294
|
+
- **Independent entities**: Users, Products, Orders, Organizations
|
|
295
|
+
- **Top-level resources**: Resources that don't belong to other entities
|
|
296
|
+
- **Simple CRUD needs**: Basic create, read, update, delete operations
|
|
297
|
+
- **Global operations**: Operations that span across the entire system
|
|
298
|
+
|
|
299
|
+
### When to Use CItemApi
|
|
300
|
+
- **Hierarchical data**: Tasks in Projects, OrderItems in Orders, Comments in Posts
|
|
301
|
+
- **Location-based operations**: Operations within specific parent contexts
|
|
302
|
+
- **Multi-tenant scenarios**: Data that belongs to specific tenants or organizations
|
|
303
|
+
- **Nested resources**: Resources that logically belong to parent resources
|
|
304
|
+
|
|
305
|
+
### Enterprise Considerations
|
|
306
|
+
- **Authentication**: Use proper bearer tokens or API keys
|
|
307
|
+
- **Rate limiting**: Implement client-side rate limiting for high-volume operations
|
|
308
|
+
- **Caching**: Cache frequently accessed data to reduce API calls
|
|
309
|
+
- **Monitoring**: Log API calls and performance metrics
|
|
310
|
+
- **Error recovery**: Implement retry logic and circuit breakers
|
|
311
|
+
- **Data validation**: Validate data before sending to API
|
|
312
|
+
|
|
313
|
+
## Running the Examples
|
|
314
|
+
|
|
315
|
+
### Prerequisites
|
|
316
|
+
```bash
|
|
317
|
+
# Install dependencies
|
|
318
|
+
npm install
|
|
319
|
+
|
|
320
|
+
# Ensure TypeScript is available
|
|
321
|
+
npm install -g tsx
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
### Run Individual Examples
|
|
325
|
+
```bash
|
|
326
|
+
# Simple example (start here)
|
|
327
|
+
npx tsx examples/simple-example.ts
|
|
328
|
+
|
|
329
|
+
# Multi-level keys example
|
|
330
|
+
npx tsx examples/multi-level-keys.ts
|
|
331
|
+
|
|
332
|
+
# Enterprise example (most comprehensive)
|
|
333
|
+
npx tsx examples/enterprise-example.ts
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
### Run All Examples
|
|
337
|
+
```bash
|
|
338
|
+
# Run all examples in sequence
|
|
339
|
+
npx tsx -e "
|
|
340
|
+
import { runSimpleExample } from './examples/simple-example.js';
|
|
341
|
+
import { runMultiLevelKeysExample } from './examples/multi-level-keys.js';
|
|
342
|
+
import { runEnterpriseExample } from './examples/enterprise-example.js';
|
|
343
|
+
|
|
344
|
+
console.log('🚀 Running All Fjell-Client-API Examples\\n');
|
|
345
|
+
|
|
346
|
+
await runSimpleExample();
|
|
347
|
+
console.log('\\n' + '='.repeat(50) + '\\n');
|
|
348
|
+
|
|
349
|
+
await runMultiLevelKeysExample();
|
|
350
|
+
console.log('\\n' + '='.repeat(50) + '\\n');
|
|
351
|
+
|
|
352
|
+
await runEnterpriseExample();
|
|
353
|
+
|
|
354
|
+
console.log('\\n✅ All examples completed successfully!');
|
|
355
|
+
"
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
## Next Steps
|
|
359
|
+
|
|
360
|
+
After exploring these examples:
|
|
361
|
+
|
|
362
|
+
1. **Read the API Documentation** - Understand the full fjell-client-api specification
|
|
363
|
+
2. **Set up your HTTP backend** - Implement corresponding server endpoints
|
|
364
|
+
3. **Configure authentication** - Set up proper API authentication for your application
|
|
365
|
+
4. **Implement error handling** - Add comprehensive error handling for production use
|
|
366
|
+
5. **Add monitoring** - Implement logging and monitoring for API operations
|
|
367
|
+
6. **Write tests** - Create tests for your specific API usage patterns
|
|
368
|
+
7. **Optimize performance** - Add caching, pagination, and other performance optimizations
|
|
369
|
+
|
|
370
|
+
## Contributing
|
|
371
|
+
|
|
372
|
+
To add new examples or improve existing ones:
|
|
373
|
+
|
|
374
|
+
1. Create your example file in `examples/`
|
|
375
|
+
2. Add corresponding integration tests in `tests/examples/`
|
|
376
|
+
3. Update this README with documentation
|
|
377
|
+
4. Ensure examples follow the established patterns
|
|
378
|
+
5. Test thoroughly with both success and error scenarios
|
|
379
|
+
|
|
380
|
+
## Support
|
|
381
|
+
|
|
382
|
+
For questions about these examples or fjell-client-api usage:
|
|
383
|
+
|
|
384
|
+
- Check the main fjell-client-api documentation
|
|
385
|
+
- Review the integration tests for detailed usage patterns
|
|
386
|
+
- Look at the enterprise example for complex workflow patterns
|
|
387
|
+
- Examine the source code for specific API method signatures
|