@fjell/express-router 4.4.56 → 4.4.57

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.
@@ -1,332 +0,0 @@
1
- # Fjell Express Router
2
-
3
- **Express Router for Fjell** - Automatic REST API generation with hierarchical data management for Express.js applications.
4
-
5
- Fjell Express Router provides a powerful abstraction layer for creating Express.js REST APIs that automatically handle CRUD operations for complex, hierarchical data models. Built on the Fjell framework, it enables rapid development of enterprise-grade APIs with built-in support for nested resources, business logic integration, and type-safe operations.
6
-
7
- ## Features
8
-
9
- - **Automatic CRUD Routes**: Generate complete REST endpoints with minimal configuration
10
- - **Hierarchical Data Support**: Handle complex nested relationships with parent-child routing
11
- - **Type-Safe Operations**: Full TypeScript support with generic type constraints
12
- - **Flexible Business Logic**: Easy integration of custom business rules and validations
13
- - **Express.js Integration**: Seamless mounting as Express middleware with full compatibility
14
- - **Built-in Error Handling**: Comprehensive error responses with proper HTTP status codes
15
- - **Extensible Architecture**: Support for custom actions, facets, and middleware
16
-
17
- ## Installation
18
-
19
- ```bash
20
- npm install @fjell/express-router
21
- ```
22
-
23
- Or with npm:
24
-
25
- ```bash
26
- npm install @fjell/express-router
27
- ```
28
-
29
- ## Quick Start
30
-
31
- ```typescript
32
- import { PItemRouter, createRegistry } from '@fjell/express-router';
33
- import { Item } from '@fjell/core';
34
- import express from 'express';
35
-
36
- // Define your data model
37
- interface User extends Item<'user'> {
38
- id: string;
39
- name: string;
40
- email: string;
41
- role: 'admin' | 'user' | 'guest';
42
- }
43
-
44
- // Create Express app and registry
45
- const app = express();
46
- const registry = createRegistry();
47
-
48
- // Create instance and router
49
- const userInstance = registry.getInstance(
50
- 'user',
51
- userOperations, // Your business logic implementation
52
- userOptions // Configuration options
53
- );
54
-
55
- const userRouter = new PItemRouter(userInstance, 'user');
56
-
57
- // Mount router - automatically creates CRUD endpoints
58
- app.use('/api/users', userRouter.getRouter());
59
-
60
- // Start server
61
- app.listen(3000, () => {
62
- console.log('Server running on http://localhost:3000');
63
- });
64
- ```
65
-
66
- This automatically creates the following endpoints:
67
-
68
- - `GET /api/users` - List all users
69
- - `GET /api/users/:userPk` - Get specific user
70
- - `POST /api/users` - Create new user
71
- - `PUT /api/users/:userPk` - Update user
72
- - `DELETE /api/users/:userPk` - Delete user
73
-
74
- ## Core Concepts
75
-
76
- ### Router Types
77
-
78
- **PItemRouter** - For primary entities that exist independently:
79
- ```typescript
80
- const userRouter = new PItemRouter(userInstance, 'user');
81
- const productRouter = new PItemRouter(productInstance, 'product');
82
- ```
83
-
84
- **CItemRouter** - For child entities that belong to parent entities:
85
- ```typescript
86
- const orderRouter = new PItemRouter(orderInstance, 'order');
87
- const orderItemRouter = new CItemRouter(orderItemInstance, 'orderItem', orderRouter);
88
- ```
89
-
90
- ### Hierarchical Routing
91
-
92
- Create nested routes for complex relationships:
93
-
94
- ```typescript
95
- // Organization -> Department -> Employee hierarchy
96
- const orgRouter = new PItemRouter(orgInstance, 'organization');
97
- const deptRouter = new CItemRouter(deptInstance, 'department', orgRouter);
98
- const empRouter = new CItemRouter(empInstance, 'employee', deptRouter);
99
-
100
- // Mount hierarchical routes
101
- app.use('/api/organizations', orgRouter.getRouter());
102
- app.use('/api/organizations/:organizationPk/departments', deptRouter.getRouter());
103
- app.use('/api/organizations/:organizationPk/departments/:departmentPk/employees', empRouter.getRouter());
104
- ```
105
-
106
- This creates endpoints like:
107
- - `GET /api/organizations/org-1/departments/dept-1/employees`
108
- - `POST /api/organizations/org-1/departments/dept-1/employees`
109
- - `GET /api/organizations/org-1/departments/dept-1/employees/emp-1`
110
-
111
- ## Advanced Usage
112
-
113
- ### Custom Business Logic
114
-
115
- Add custom routes alongside automatic CRUD operations:
116
-
117
- ```typescript
118
- const router = userRouter.getRouter();
119
-
120
- // Add custom business logic routes
121
- router.get('/analytics', async (req, res) => {
122
- const analytics = await userInstance.operations.getAnalytics();
123
- res.json(analytics);
124
- });
125
-
126
- router.post('/:userPk/activate', async (req, res) => {
127
- const userPk = req.params.userPk;
128
- const user = await userInstance.operations.activate(userPk);
129
- res.json(user);
130
- });
131
-
132
- app.use('/api/users', router);
133
- ```
134
-
135
- ### Middleware Integration
136
-
137
- Add Express middleware for authentication, validation, and more:
138
-
139
- ```typescript
140
- import { authenticate, authorize, validateRequest } from './middleware';
141
-
142
- // Global middleware
143
- app.use(express.json());
144
- app.use(authenticate);
145
-
146
- // Router-specific middleware
147
- const protectedRouter = userRouter.getRouter();
148
- protectedRouter.use(authorize(['admin', 'user']));
149
- protectedRouter.use('/sensitive-endpoint', validateRequest);
150
-
151
- app.use('/api/users', protectedRouter);
152
- ```
153
-
154
- ### Error Handling
155
-
156
- Built-in error handling with proper HTTP status codes:
157
-
158
- ```typescript
159
- // Automatic error responses for common scenarios:
160
- // 404 - Entity not found
161
- // 400 - Invalid request data
162
- // 500 - Internal server errors
163
-
164
- // Custom error handling
165
- app.use((err, req, res, next) => {
166
- console.error('API Error:', err);
167
- res.status(err.status || 500).json({
168
- error: err.message || 'Internal Server Error',
169
- ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
170
- });
171
- });
172
- ```
173
-
174
- ## Data Model Requirements
175
-
176
- Your data models must extend the Fjell `Item` interface:
177
-
178
- ```typescript
179
- import { Item, UUID } from '@fjell/core';
180
-
181
- interface User extends Item<'user'> {
182
- id: string;
183
- name: string;
184
- email: string;
185
- // ... other properties
186
- }
187
-
188
- interface Order extends Item<'order'> {
189
- id: string;
190
- customerId: string;
191
- total: number;
192
- // ... other properties
193
- }
194
-
195
- interface OrderItem extends Item<'orderItem', 'order'> {
196
- id: string;
197
- productId: string;
198
- quantity: number;
199
- price: number;
200
- // ... other properties
201
- }
202
- ```
203
-
204
- ## Configuration
205
-
206
- Configure your instances with business operations and options:
207
-
208
- ```typescript
209
- const userInstance = registry.getInstance(
210
- 'user',
211
- {
212
- // Business operations implementation
213
- create: async (item) => { /* create logic */ },
214
- get: async (pk) => { /* get logic */ },
215
- update: async (pk, updates) => { /* update logic */ },
216
- delete: async (pk) => { /* delete logic */ },
217
- list: async (query) => { /* list logic */ },
218
- // ... other operations
219
- },
220
- {
221
- // Configuration options
222
- allowedMethods: ['GET', 'POST', 'PUT', 'DELETE'],
223
- validation: { /* validation rules */ },
224
- facets: { /* custom facets */ },
225
- actions: { /* custom actions */ },
226
- // ... other options
227
- }
228
- );
229
- ```
230
-
231
- ## Examples
232
-
233
- This package includes comprehensive examples in the `examples/` directory:
234
-
235
- - **`basic-router-example.ts`** - Start here for fundamental usage patterns
236
- - **`nested-router-example.ts`** - Hierarchical data management with organizations/departments/employees
237
- - **`full-application-example.ts`** - Production-ready e-commerce application
238
-
239
- Run examples:
240
-
241
- ```bash
242
- # Basic example
243
- npx tsx examples/basic-router-example.ts
244
-
245
- # Nested routing example
246
- npx tsx examples/nested-router-example.ts
247
-
248
- # Full application example
249
- npx tsx examples/full-application-example.ts
250
- ```
251
-
252
- ## API Reference
253
-
254
- ### PItemRouter<T, S>
255
-
256
- Primary item router for top-level entities.
257
-
258
- **Constructor**
259
- ```typescript
260
- new PItemRouter<T, S>(instance: Instance<T, S>, keyType: S, options?: ItemRouterOptions)
261
- ```
262
-
263
- **Methods**
264
- - `getRouter(): Router` - Get Express router instance
265
- - `getPkType(): S` - Get primary key type
266
- - `createItem(req, res)` - Handle POST requests
267
- - `getItem(req, res)` - Handle GET requests for single items
268
- - `updateItem(req, res)` - Handle PUT requests
269
- - `deleteItem(req, res)` - Handle DELETE requests
270
-
271
- ### CItemRouter<T, S, L1, ...>
272
-
273
- Child item router for nested entities.
274
-
275
- **Constructor**
276
- ```typescript
277
- new CItemRouter<T, S, L1>(
278
- instance: Instance<T, S, L1>,
279
- keyType: S,
280
- parentRouter: ItemRouter<L1>,
281
- options?: ItemRouterOptions
282
- )
283
- ```
284
-
285
- Inherits all methods from `ItemRouter` with additional parent-child relationship handling.
286
-
287
- ### createRegistry()
288
-
289
- Factory function to create a new registry instance for managing multiple routers.
290
-
291
- ```typescript
292
- const registry = createRegistry();
293
- const instance = registry.getInstance(keyType, operations, options);
294
- ```
295
-
296
- ## Requirements
297
-
298
- - Node.js >= 21
299
- - TypeScript >= 5.0
300
- - Express.js >= 5.0
301
-
302
- ## Dependencies
303
-
304
- - `@fjell/core` - Core Fjell framework types and utilities
305
- - `@fjell/lib` - Fjell library components
306
- - `@fjell/logging` - Structured logging for Fjell applications
307
- - `@fjell/registry` - Registry management for Fjell instances
308
- - `express` - Express.js web framework
309
- - `deepmerge` - Deep object merging utility
310
-
311
- ## Contributing
312
-
313
- Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.
314
-
315
- 1. Fork the repository
316
- 2. Create a feature branch
317
- 3. Make your changes with tests
318
- 4. Ensure all tests pass
319
- 5. Submit a pull request
320
-
321
- ## License
322
-
323
- Licensed under the Apache License 2.0. See the LICENSE file for details.
324
-
325
- ## Support
326
-
327
- - **Documentation**: [Full documentation and guides](./docs/)
328
- - **Examples**: [Comprehensive examples](./examples/)
329
- - **Issues**: [GitHub Issues](https://github.com/getfjell/express-router/issues)
330
- - **Discussions**: [GitHub Discussions](https://github.com/getfjell/express-router/discussions)
331
-
332
- Built with care by the Fjell team.
@@ -1,339 +0,0 @@
1
- # Fjell-Express-Router Examples
2
-
3
- This directory contains examples demonstrating how to use fjell-express-router for building Express.js applications with automatic CRUD routing, hierarchical data management, and business logic integration with different patterns and complexity levels.
4
-
5
- ## Examples
6
-
7
- ### 1. `basic-router-example.ts` ⭐ **Start Here!**
8
- **Perfect for beginners!** Demonstrates the fundamental way to use fjell-express-router for REST API development:
9
- - **Basic PItemRouter usage** - Create routers for primary entities (Users, Tasks)
10
- - **Automatic CRUD endpoints** - GET, POST, PUT, DELETE routes generated automatically
11
- - **Mock data operations** - Simple in-memory storage with business logic
12
- - **Express app integration** - Mount routers and add custom middleware
13
- - **Custom business routes** - Dashboard and health check endpoints
14
-
15
- Great for understanding the fundamentals of fjell-express-router for REST API development.
16
-
17
- ### 2. `nested-router-example.ts` 🏗️ **Hierarchical Data Management**
18
- **Advanced hierarchical routing!** Demonstrates complex data structures with nested relationships:
19
- - **Multiple router types**: PItemRouter for Organizations, CItemRouter for Departments and Employees
20
- - **Nested route mounting**: `/organizations/:orgId/departments/:deptId/employees/:empId`
21
- - **Hierarchical data models**: Organization → Department → Employee relationships
22
- - **Location-based operations**: Complex queries spanning multiple organizational levels
23
- - **Business analytics**: Organizational hierarchy summaries and statistics
24
-
25
- Shows how fjell-express-router handles enterprise organizational data patterns with deep hierarchies.
26
-
27
- ### 3. `full-application-example.ts` 🚀 **Production-Ready Application**
28
- **Complete enterprise application!** Demonstrates a realistic e-commerce system with advanced patterns:
29
- - **Multiple interconnected entities**: Customer, Product, Order, OrderItem, Review
30
- - **Advanced middleware**: Error handling, request logging, business validation
31
- - **Complex business logic**: Product catalog, customer analytics, order management
32
- - **Production patterns**: CORS headers, security middleware, proper error handling
33
- - **Real-world scenarios**: Complete e-commerce platform with customer lifecycle management
34
-
35
- Perfect for understanding how to build production-ready applications with fjell-express-router.
36
-
37
- ## Key Concepts Demonstrated
38
-
39
- ### Basic Router Setup (basic-router-example.ts)
40
- ```typescript
41
- // Import fjell-express-router functionality
42
- import { PItemRouter, createRegistry } from '@fjell/express-router';
43
- import express from 'express';
44
-
45
- // Create Express app and registry
46
- const app = express();
47
- const registry = createRegistry();
48
-
49
- // Create router instance
50
- const userRouter = new PItemRouter(userInstance, 'user');
51
-
52
- // Mount router to create automatic REST endpoints
53
- app.use('/api/users', userRouter.getRouter());
54
- // This creates:
55
- // GET /api/users - List all users
56
- // GET /api/users/:userPk - Get specific user
57
- // POST /api/users - Create new user
58
- // PUT /api/users/:userPk - Update user
59
- // DELETE /api/users/:userPk - Delete user
60
- ```
61
-
62
- ### Nested Routing (nested-router-example.ts)
63
- ```typescript
64
- // Create hierarchical routers
65
- const orgRouter = new PItemRouter(orgInstance, 'organization');
66
- const deptRouter = new CItemRouter(deptInstance, 'department', orgRouter);
67
- const empRouter = new CItemRouter(empInstance, 'employee', deptRouter);
68
-
69
- // Mount nested routes
70
- app.use('/api/organizations', orgRouter.getRouter());
71
- app.use('/api/organizations/:organizationPk/departments', deptRouter.getRouter());
72
- app.use('/api/organizations/:organizationPk/departments/:departmentPk/employees', empRouter.getRouter());
73
-
74
- // This creates nested endpoints like:
75
- // GET /api/organizations/org-1/departments/dept-1/employees
76
- // POST /api/organizations/org-1/departments/dept-1/employees
77
- ```
78
-
79
- ### Production Application (full-application-example.ts)
80
- ```typescript
81
- // Advanced middleware setup
82
- app.use(express.json({ limit: '10mb' }));
83
- app.use(requestLogger);
84
- app.use(validateCustomerTier);
85
- app.use(errorHandler);
86
-
87
- // Business logic routes
88
- app.get('/api/dashboard', async (req, res) => {
89
- // Complex dashboard with analytics
90
- });
91
-
92
- app.get('/api/catalog', async (req, res) => {
93
- // Product catalog with filtering and search
94
- });
95
- ```
96
-
97
- ## Data Model Patterns
98
-
99
- ### Primary Items (PItemRouter)
100
- Primary items are top-level entities that exist independently:
101
- ```typescript
102
- interface User extends Item<'user'> {
103
- id: string;
104
- name: string;
105
- email: string;
106
- // ... other properties
107
- }
108
-
109
- // Creates routes: /api/users, /api/users/:userPk
110
- const userRouter = new PItemRouter(userInstance, 'user');
111
- ```
112
-
113
- ### Contained Items (CItemRouter)
114
- Contained items exist within a parent context and inherit location:
115
- ```typescript
116
- interface Department extends Item<'department', 'organization'> {
117
- id: string;
118
- name: string;
119
- organizationId: string; // Reference to parent
120
- // ... other properties
121
- }
122
-
123
- // Creates nested routes: /api/organizations/:orgPk/departments
124
- const deptRouter = new CItemRouter(deptInstance, 'department', orgRouter);
125
- ```
126
-
127
- ### Multi-Level Hierarchies
128
- Deep nesting is supported for complex organizational structures:
129
- ```typescript
130
- interface Employee extends Item<'employee', 'organization', 'department'> {
131
- id: string;
132
- name: string;
133
- organizationId: string;
134
- departmentId: string;
135
- // ... other properties
136
- }
137
-
138
- // Creates deeply nested routes: /api/organizations/:orgPk/departments/:deptPk/employees
139
- const empRouter = new CItemRouter(empInstance, 'employee', deptRouter);
140
- ```
141
-
142
- ## Running the Examples
143
-
144
- ### Prerequisites
145
- ```bash
146
- # Install dependencies
147
- npm install express @fjell/core @fjell/lib @fjell/express-router
148
-
149
- # For running TypeScript examples
150
- npm install -g tsx
151
- ```
152
-
153
- ### Running Individual Examples
154
-
155
- **Basic Router Example:**
156
- ```bash
157
- npx tsx examples/basic-router-example.ts
158
- # Server runs on http://localhost:3001
159
- ```
160
-
161
- **Nested Router Example:**
162
- ```bash
163
- npx tsx examples/nested-router-example.ts
164
- # Server runs on http://localhost:3002
165
- ```
166
-
167
- **Full Application Example:**
168
- ```bash
169
- npx tsx examples/full-application-example.ts
170
- # Server runs on http://localhost:3003
171
- ```
172
-
173
- ## Testing the Examples
174
-
175
- ### Basic Router Example (Port 3001)
176
- ```bash
177
- # Health check
178
- curl http://localhost:3001/api/health
179
-
180
- # Dashboard summary
181
- curl http://localhost:3001/api/dashboard
182
-
183
- # List all users
184
- curl http://localhost:3001/api/users
185
-
186
- # Get specific user
187
- curl http://localhost:3001/api/users/user-1
188
-
189
- # Create new user
190
- curl -X POST http://localhost:3001/api/users \
191
- -H "Content-Type: application/json" \
192
- -d '{"name":"New User","email":"new@example.com","role":"user"}'
193
-
194
- # List all tasks
195
- curl http://localhost:3001/api/tasks
196
- ```
197
-
198
- ### Nested Router Example (Port 3002)
199
- ```bash
200
- # Organizational hierarchy
201
- curl http://localhost:3002/api/hierarchy
202
-
203
- # Statistics summary
204
- curl http://localhost:3002/api/stats
205
-
206
- # List organizations
207
- curl http://localhost:3002/api/organizations
208
-
209
- # List departments for organization
210
- curl http://localhost:3002/api/organizations/org-1/departments
211
-
212
- # List employees for department
213
- curl http://localhost:3002/api/organizations/org-1/departments/dept-1/employees
214
-
215
- # Create new department
216
- curl -X POST http://localhost:3002/api/organizations/org-1/departments \
217
- -H "Content-Type: application/json" \
218
- -d '{"name":"IT Department","budget":1000000,"headCount":15}'
219
- ```
220
-
221
- ### Full Application Example (Port 3003)
222
- ```bash
223
- # System health
224
- curl http://localhost:3003/health
225
-
226
- # Business dashboard
227
- curl http://localhost:3003/api/dashboard
228
-
229
- # Product catalog
230
- curl http://localhost:3003/api/catalog
231
-
232
- # Filtered catalog
233
- curl "http://localhost:3003/api/catalog?category=Electronics&featured=true"
234
-
235
- # Customer analytics
236
- curl http://localhost:3003/api/customers/cust-1/analytics
237
-
238
- # List customers
239
- curl http://localhost:3003/api/customers
240
-
241
- # Customer orders
242
- curl http://localhost:3003/api/customers/cust-1/orders
243
-
244
- # Create new customer
245
- curl -X POST http://localhost:3003/api/customers \
246
- -H "Content-Type: application/json" \
247
- -d '{
248
- "name": "New Customer",
249
- "email": "customer@example.com",
250
- "phone": "+1-555-0789",
251
- "address": {
252
- "street": "789 Pine St",
253
- "city": "Seattle",
254
- "state": "WA",
255
- "zipCode": "98101"
256
- },
257
- "tier": "bronze"
258
- }'
259
- ```
260
-
261
- ## Integration Patterns
262
-
263
- ### Mock Operations
264
- All examples use mock operations that simulate real database interactions:
265
- ```typescript
266
- const createUserOperations = () => ({
267
- async all() { /* return all users */ },
268
- async get(key) { /* return specific user */ },
269
- async create(item) { /* create new user */ },
270
- async update(key, updates) { /* update user */ },
271
- async remove(key) { /* delete user */ },
272
- async find(finder, params) { /* find users with criteria */ }
273
- });
274
- ```
275
-
276
- ### Instance Creation
277
- Fjell instances wrap operations and provide router integration:
278
- ```typescript
279
- const mockUserInstance = {
280
- operations: createUserOperations(),
281
- options: {}
282
- };
283
-
284
- const userRouter = new PItemRouter(mockUserInstance, 'user');
285
- ```
286
-
287
- ### Error Handling
288
- Production applications should include comprehensive error handling:
289
- ```typescript
290
- const errorHandler = (err, req, res, next) => {
291
- console.error('Application Error:', err.message);
292
- res.status(500).json({
293
- error: 'Internal Server Error',
294
- message: process.env.NODE_ENV === 'development' ? err.message : 'Something went wrong'
295
- });
296
- };
297
-
298
- app.use(errorHandler);
299
- ```
300
-
301
- ## Best Practices
302
-
303
- ### 1. **Start Simple**
304
- Begin with the basic router example to understand core concepts before moving to complex hierarchies.
305
-
306
- ### 2. **Design Your Data Model**
307
- Plan your Item interfaces and relationships carefully:
308
- - Use PItemRouter for independent entities
309
- - Use CItemRouter for entities that belong to parents
310
- - Define clear location hierarchies for nested data
311
-
312
- ### 3. **Implement Operations**
313
- Create comprehensive operations that handle:
314
- - CRUD operations (all, get, create, update, remove)
315
- - Business logic finders (find method with custom logic)
316
- - Error handling and validation
317
-
318
- ### 4. **Add Business Logic**
319
- Extend beyond basic CRUD with:
320
- - Custom middleware for validation
321
- - Business logic routes (dashboards, analytics)
322
- - Proper error handling and logging
323
-
324
- ### 5. **Production Considerations**
325
- For production applications:
326
- - Implement proper authentication/authorization
327
- - Add rate limiting and security headers
328
- - Use environment-specific configurations
329
- - Implement comprehensive logging and monitoring
330
-
331
- ## Next Steps
332
-
333
- 1. **Study the examples** in order of complexity
334
- 2. **Run each example** and test the endpoints
335
- 3. **Modify the data models** to match your use case
336
- 4. **Implement real operations** with your database/API
337
- 5. **Add authentication and security** for production use
338
-
339
- For more advanced usage, see the fjell-express-router documentation and explore other fjell ecosystem packages like fjell-cache, fjell-lib, and fjell-client-api.
@@ -1 +0,0 @@
1
-
Binary file
@@ -1,6 +0,0 @@
1
- {
2
- "extends": "@fjell/docs-template/tsconfig.node.json",
3
- "compilerOptions": {
4
- "noEmit": true
5
- }
6
- }