express-sweet 3.0.2 → 4.0.0

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 (40) hide show
  1. package/CHANGELOG.md +112 -118
  2. package/README.md +206 -57
  3. package/configuration_sample/cjs/config.js +5 -4
  4. package/configuration_sample/cjs/upload.js +91 -0
  5. package/configuration_sample/esm/config.js +5 -4
  6. package/configuration_sample/esm/upload.js +91 -0
  7. package/dist/build.cjs +41 -35
  8. package/dist/build.mjs +41 -35
  9. package/package.json +6 -4
  10. package/types/database/Model.d.ts +2 -2
  11. package/types/handlebars_helpers/object.d.ts +2 -2
  12. package/types/index.d.ts +1 -43
  13. package/types/interfaces/{BasicConfig.d.ts → AppConfig.d.ts} +8 -7
  14. package/types/interfaces/DatabaseConfig.d.ts +1 -0
  15. package/types/interfaces/UploadConfig.d.ts +73 -0
  16. package/types/interfaces/index.d.ts +6 -2
  17. package/types/middlewares/corsPolicy.d.ts +28 -0
  18. package/types/middlewares/{Environment.d.ts → envLoader.d.ts} +13 -15
  19. package/types/middlewares/errorHandler.d.ts +32 -0
  20. package/types/middlewares/globalVars.d.ts +25 -0
  21. package/types/middlewares/index.d.ts +19 -11
  22. package/types/middlewares/localVars.d.ts +44 -0
  23. package/types/middlewares/passportAuth.d.ts +15 -0
  24. package/types/middlewares/requestParser.d.ts +27 -0
  25. package/types/{routing/Router.d.ts → middlewares/routeMapper.d.ts} +14 -16
  26. package/types/middlewares/viewEngine.d.ts +49 -0
  27. package/types/mount.d.ts +33 -1
  28. package/types/utils/Types.d.ts +17 -11
  29. package/types/utils/index.d.ts +7 -3
  30. package/types/utils/loadAppConfig.d.ts +17 -0
  31. package/types/utils/loadUploadConfig.d.ts +20 -0
  32. package/types/middlewares/Authentication.d.ts +0 -52
  33. package/types/middlewares/CORS.d.ts +0 -30
  34. package/types/middlewares/ErrorHandler.d.ts +0 -34
  35. package/types/middlewares/Global.d.ts +0 -27
  36. package/types/middlewares/Http.d.ts +0 -29
  37. package/types/middlewares/Local.d.ts +0 -42
  38. package/types/middlewares/View.d.ts +0 -49
  39. package/types/routing/index.d.ts +0 -37
  40. package/types/utils/loadBasicConfig.d.ts +0 -17
package/README.md CHANGED
@@ -2,58 +2,40 @@
2
2
 
3
3
  EXPRESS SWEET is a powerful Express.js extension that streamlines your development workflow and boosts productivity with a comprehensive suite of utilities and enhancements.
4
4
 
5
- - [EXPRESS SWEET](#express-sweet)
6
- - [Features](#features)
7
- - [API Reference](#api-reference)
8
- - [EXPRESS SWEET Generator](#express-sweet-generator)
9
- - [Quick Start](#quick-start)
10
- - [Database Setup](#database-setup)
11
- - [Database Configuration](#database-configuration)
12
- - [Environment Configuration](#environment-configuration)
13
- - [Running the Application](#running-the-application)
14
- - [Project Structure](#project-structure)
15
- - [Key Directories Explained](#key-directories-explained)
16
- - [Configuration](#configuration)
17
- - [Environment Variables](#environment-variables)
18
- - [Base Configuration (`config/config.js`)](#base-configuration-configconfigjs)
19
- - [Database Configuration (`config/database.js`)](#database-configuration-configdatabasejs)
20
- - [Authentication Configuration (`config/authentication.js`)](#authentication-configuration-configauthenticationjs)
21
- - [View Configuration (`config/view.js`)](#view-configuration-configviewjs)
22
- - [Logging Configuration (`config/logging.js`)](#logging-configuration-configloggingjs)
23
- - [Routing](#routing)
24
- - [Basic Routing](#basic-routing)
25
- - [Nested Routing](#nested-routing)
26
- - [Default Routing](#default-routing)
27
- - [Routing Methods](#routing-methods)
28
- - [Model](#model)
29
- - [Accessing Models](#accessing-models)
30
- - [Creating Custom Models](#creating-custom-models)
31
- - [Model Relationships](#model-relationships)
32
- - [View System](#view-system)
33
- - [Layout Usage](#layout-usage)
34
- - [Template Syntax](#template-syntax)
35
- - [Handlebars Helpers](#handlebars-helpers)
36
- - [Array Helpers](#array-helpers)
37
- - [Comparison Helpers](#comparison-helpers)
38
- - [HTML Helpers](#html-helpers)
39
- - [Object Helpers](#object-helpers)
40
- - [String Helpers](#string-helpers)
41
- - [Date Helpers](#date-helpers)
42
- - [Number Helpers](#number-helpers)
43
- - [Math Helpers](#math-helpers)
44
- - [Authentication](#authentication)
45
- - [Login Example](#login-example)
46
- - [Asynchronous Login (Ajax)](#asynchronous-login-ajax)
47
- - [Synchronous Login (Form Submit)](#synchronous-login-form-submit)
48
- - [Logout Example](#logout-example)
49
- - [Examples](#examples)
50
- - [RESTful API Development](#restful-api-development)
51
- - [Advanced View Usage](#advanced-view-usage)
52
- - [Environment-Specific Configuration](#environment-specific-configuration)
53
- - [Error Handling](#error-handling)
54
- - [Release Notes](#release-notes)
55
- - [Author](#author)
56
- - [License](#license)
5
+ ## Now Supports Express 5!
6
+
7
+ **Version 4.0+ brings full Express 5 compatibility with production-ready solutions for common migration challenges:**
8
+
9
+ - **Express 4 Query Parser Behavior** - Nested query objects work seamlessly (e.g., `?user[email]=test@example.com` → `req.query.user.email`)
10
+ - Solves the `[Object: null prototype]` issue ([#3472](https://github.com/expressjs/express/issues/3472), [#599](https://github.com/cdimascio/express-openapi-validator/issues/599))
11
+ - Automatic `query parser: 'extended'` configuration out of the box
12
+ - **Multipart Form Data Support** - Handle file uploads and form submissions effortlessly
13
+ - Built-in `multer().none()` middleware for forms without files
14
+ - Dynamic file upload configuration via `config/upload.js`
15
+ - **Modern Route Patterns** - Full support for RegExp with named capture groups
16
+ - Migrated from deprecated `/:id(\\d+)` to `/^\/(?<id>\\d+)$/` syntax
17
+ - **Node.js 18+ Ready** - Leverages the latest Node.js LTS features
18
+
19
+ For more details on Express 5 changes, see the [Express.js Release Notes](https://expressjs.com/en/changelog/).
20
+
21
+ ## Table of Contents
22
+
23
+ - [Now Supports Express 5!](#now-supports-express-5)
24
+ - [Features](#features)
25
+ - [Demos](#demos)
26
+ - [API Reference](#api-reference)
27
+ - [EXPRESS SWEET Generator](#express-sweet-generator)
28
+ - [Quick Start](#quick-start)
29
+ - [Project Structure](#project-structure)
30
+ - [Configuration](#configuration)
31
+ - [Routing](#routing)
32
+ - [Model](#model)
33
+ - [View System](#view-system)
34
+ - [Authentication](#authentication)
35
+ - [Examples](#examples)
36
+ - [Release Notes](#release-notes)
37
+ - [Author](#author)
38
+ - [License](#license)
57
39
 
58
40
  ## Features
59
41
 
@@ -68,9 +50,19 @@ EXPRESS SWEET provides the following key features to accelerate your development
68
50
  - **CORS Support**: Built-in Cross-Origin Resource Sharing support
69
51
  - **Project Generator**: Command-line tool to quickly scaffold new applications
70
52
 
53
+ ## Demos
54
+
55
+ The `demo/` directory contains working examples that demonstrate different use cases of EXPRESS SWEET:
56
+
57
+ - **REST API Demo** - Modern REST API with CORS support and Bearer token authentication, ideal for SPAs and mobile app backends
58
+ - **TODO Demo** - Full-stack application with authentication, database integration, and async operations
59
+ - **File Upload Demo** - File upload handling with Multer middleware for single and multiple file uploads
60
+
61
+ See the [demo README](https://github.com/takuya-motoshima/express-sweet/tree/main/demo) for complete details and screenshots.
62
+
71
63
  ## API Reference
72
64
 
73
- 📖 **[Complete API Documentation](https://takuya-motoshima.github.io/express-sweet/)**
65
+ **[Complete API Documentation](https://takuya-motoshima.github.io/express-sweet/)**
74
66
 
75
67
  The comprehensive API reference includes detailed documentation for:
76
68
 
@@ -86,9 +78,12 @@ The comprehensive API reference includes detailed documentation for:
86
78
  - **[Object](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.object.html)**: `jsonStringify`, `jsonParse`
87
79
  - **[HTML](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.html.html)**: `cacheBusting`, `stripTags`
88
80
  - **[Layouts](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.layouts.html)**: `block`, `contentFor`
89
- - **[Configuration Interfaces](https://takuya-motoshima.github.io/express-sweet/modules/interfaces.html)**: TypeScript interfaces for `AuthenticationConfig`, `BasicConfig`, `DatabaseConfig`, `LoggingConfig`, `ViewConfig`
90
- - **[Middlewares](https://takuya-motoshima.github.io/express-sweet/modules/middlewares.html)**: `CORS`, `Environment`, `ErrorHandler`, `Global`, `Http`, `Local`, `View`
91
- - **[Routing](https://takuya-motoshima.github.io/express-sweet/modules/routing.html)**: `Router` class for advanced routing functionality
81
+ - **[Configuration Interfaces](https://takuya-motoshima.github.io/express-sweet/modules/interfaces.html)**: TypeScript interfaces for:
82
+ - `AuthenticationConfig`, `AppConfig`, `DatabaseConfig`
83
+ - `LoggingConfig`, `ViewConfig`, `UploadConfig`
84
+ - **[Middlewares](https://takuya-motoshima.github.io/express-sweet/modules/middlewares.html)**: Core middleware functions:
85
+ - `corsPolicy`, `envLoader`, `errorHandler`, `globalVars`
86
+ - `requestParser`, `localVars`, `viewEngine`, `passportAuth`, `routeMapper`
92
87
  - **[Utilities](https://takuya-motoshima.github.io/express-sweet/modules/utils.html)**: Type checking functions and configuration loaders
93
88
  - **[Mount Function](https://takuya-motoshima.github.io/express-sweet/variables/mount.html)**: Application initialization and setup
94
89
 
@@ -128,6 +123,9 @@ Use the application generator tool, `express-sweet-generator`, to quickly create
128
123
  npm install
129
124
  ```
130
125
 
126
+ <details>
127
+ <summary><strong>Quick Start</strong></summary>
128
+
131
129
  ## Quick Start
132
130
 
133
131
  ### Database Setup
@@ -258,6 +256,11 @@ npm start
258
256
 
259
257
  Then open `http://localhost:3000/` in your browser to access the application.
260
258
 
259
+ </details>
260
+
261
+ <details>
262
+ <summary><strong>Project Structure</strong></summary>
263
+
261
264
  ## Project Structure
262
265
 
263
266
  The generated application has the following directory structure:
@@ -280,6 +283,7 @@ The generated application has the following directory structure:
280
283
  │ ├── config.js # Core application configuration
281
284
  │ ├── database.js # Database connection settings
282
285
  │ ├── logging.js # HTTP request logging configuration
286
+ │ ├── upload.js # File upload configuration
283
287
  │ └── view.js # Template engine configuration
284
288
  ├── errors # Custom error classes
285
289
  │ └── UserNotFound.js # Custom error definitions
@@ -325,9 +329,14 @@ URL endpoint handlers organized by feature. The file structure automatically map
325
329
  **Views (`views/`)**
326
330
  Handlebars templates for rendering HTML pages. The `layout/` directory contains base templates, while `partials/` holds reusable components.
327
331
 
328
- **Public (`public/`)**
332
+ **Public (`public/`)**
329
333
  Static files served directly by the web server. The `build/` directory contains compiled frontend assets, while `upload/` stores user-generated content.
330
334
 
335
+ </details>
336
+
337
+ <details>
338
+ <summary><strong>Configuration</strong></summary>
339
+
331
340
  ## Configuration
332
341
 
333
342
  EXPRESS SWEET uses several configuration files to customize application behavior. Each configuration file corresponds to a specific aspect of the framework:
@@ -428,6 +437,124 @@ HTTP request logging settings are defined in the `config/logging.js` file.
428
437
  - [ESM Configuration](configuration_sample/esm/logging.js)
429
438
  - [CJS Configuration](configuration_sample/cjs/logging.js)
430
439
 
440
+ ### Upload Configuration (`config/upload.js`)
441
+
442
+ File upload settings using Multer are defined in the `config/upload.js` file.
443
+
444
+ **Sample configurations:**
445
+ - [ESM Configuration](configuration_sample/esm/upload.js)
446
+ - [CJS Configuration](configuration_sample/cjs/upload.js)
447
+
448
+ **Configuration Options:**
449
+
450
+ - **`enabled: boolean`**
451
+ Enable file upload middleware. Defaults to `false`.
452
+ If `config/upload.js` doesn't exist, upload middleware won't be applied.
453
+
454
+ - **`resolve_middleware: (req: express.Request, multer: typeof import('multer')) => Function|null`**
455
+ Hook function to dynamically resolve multer middleware based on request.
456
+ Return a multer middleware instance or `null` to skip upload handling for the request.
457
+
458
+ **Storage Options:**
459
+
460
+ - **Memory Storage** (`multer.memoryStorage()`): Stores files in memory as Buffer objects. Fast and suitable for small files or when you need to process files immediately.
461
+ - **Disk Storage** (`multer.diskStorage()`): Stores files on disk. Better for large files or when you need persistent storage.
462
+
463
+ **Configuration Examples:**
464
+
465
+ ```js
466
+ // Single file upload
467
+ resolve_middleware: (req, multer) => {
468
+ if (req.path === '/api/user/avatar' && req.method === 'POST') {
469
+ const upload = multer({ storage: multer.memoryStorage() });
470
+ return upload.single('avatar');
471
+ }
472
+ return null;
473
+ }
474
+
475
+ // Multiple files with same field name
476
+ resolve_middleware: (req, multer) => {
477
+ if (req.path === '/api/gallery' && req.method === 'POST') {
478
+ const upload = multer({ storage: multer.memoryStorage() });
479
+ return upload.array('photos', 10);
480
+ }
481
+ return null;
482
+ }
483
+
484
+ // Multiple file fields
485
+ resolve_middleware: (req, multer) => {
486
+ if (req.path === '/api/admin/firms' && req.method === 'POST') {
487
+ const upload = multer({ storage: multer.memoryStorage() });
488
+ return upload.fields([
489
+ { name: 'logo', maxCount: 1 },
490
+ { name: 'eyecatch', maxCount: 1 }
491
+ ]);
492
+ }
493
+ return null;
494
+ }
495
+ ```
496
+
497
+ **Accessing Uploaded Files in Routes:**
498
+
499
+ ```js
500
+ import {Router} from 'express';
501
+
502
+ const router = Router();
503
+
504
+ // Single file upload
505
+ router.post('/avatar', (req, res) => {
506
+ if (!req.file) {
507
+ return res.status(400).json({ error: 'No file uploaded' });
508
+ }
509
+
510
+ // Access file properties
511
+ console.log(req.file.originalname); // Original filename
512
+ console.log(req.file.mimetype); // MIME type
513
+ console.log(req.file.size); // File size in bytes
514
+ console.log(req.file.buffer); // File data (memory storage)
515
+
516
+ res.json({ success: true, filename: req.file.originalname });
517
+ });
518
+
519
+ // Multiple files (array)
520
+ router.post('/gallery', (req, res) => {
521
+ if (!req.files || req.files.length === 0) {
522
+ return res.status(400).json({ error: 'No files uploaded' });
523
+ }
524
+
525
+ // Access files array
526
+ req.files.forEach(file => {
527
+ console.log(file.originalname);
528
+ });
529
+
530
+ res.json({ success: true, count: req.files.length });
531
+ });
532
+
533
+ // Multiple fields
534
+ router.post('/firms', (req, res) => {
535
+ if (!req.files) {
536
+ return res.status(400).json({ error: 'No files uploaded' });
537
+ }
538
+
539
+ // Access specific fields
540
+ const logo = req.files['logo'] ? req.files['logo'][0] : null;
541
+ const eyecatch = req.files['eyecatch'] ? req.files['eyecatch'][0] : null;
542
+
543
+ res.json({
544
+ success: true,
545
+ logo: logo ? logo.originalname : null,
546
+ eyecatch: eyecatch ? eyecatch.originalname : null
547
+ });
548
+ });
549
+
550
+ export default router;
551
+ ```
552
+
553
+ </details>
554
+
555
+ <details>
556
+ <summary><strong>Routing</strong></summary>
557
+
431
558
  ## Routing
432
559
 
433
560
  Routing determines how an application responds to client requests for specific endpoints, defined by a URI path and HTTP request method (GET, POST, etc.).
@@ -495,6 +622,11 @@ Express supports routing methods corresponding to HTTP methods:
495
622
 
496
623
  For comprehensive routing documentation, see the [Express Routing Guide](https://expressjs.com/en/guide/routing.html#express-router).
497
624
 
625
+ </details>
626
+
627
+ <details>
628
+ <summary><strong>Model</strong></summary>
629
+
498
630
  ## Model
499
631
 
500
632
  Models provide a structured way to interact with specific database tables in your application. EXPRESS SWEET provides a [Sequelize](https://sequelize.org/docs/v6/)-based model class that offers powerful features including:
@@ -603,6 +735,11 @@ static associate(models) {
603
735
 
604
736
  For comprehensive model documentation and advanced features, see the [Model API Reference](https://takuya-motoshima.github.io/express-sweet/modules/database.html).
605
737
 
738
+ </details>
739
+
740
+ <details>
741
+ <summary><strong>View System</strong></summary>
742
+
606
743
  ## View System
607
744
 
608
745
  EXPRESS SWEET uses Handlebars as its template engine with automatic layout support and a rich set of custom helpers.
@@ -786,6 +923,11 @@ Mathematical operations for template calculations:
786
923
 
787
924
  For complete documentation of all helpers and their options, see the [Handlebars Helpers API Reference](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.html).
788
925
 
926
+ </details>
927
+
928
+ <details>
929
+ <summary><strong>Authentication</strong></summary>
930
+
789
931
  ## Authentication
790
932
 
791
933
  EXPRESS SWEET includes built-in Passport authentication middleware for username and password authentication. You can immediately implement user authentication using the authentication configuration file and authentication service module.
@@ -899,6 +1041,11 @@ export default router;
899
1041
 
900
1042
  For detailed authentication configuration options, see the [Configuration](#configuration) section and [Authentication API Reference](https://takuya-motoshima.github.io/express-sweet/classes/services.Authentication.html).
901
1043
 
1044
+ </details>
1045
+
1046
+ <details>
1047
+ <summary><strong>Examples</strong></summary>
1048
+
902
1049
  ## Examples
903
1050
 
904
1051
  ### RESTful API Development
@@ -1143,6 +1290,8 @@ router.post('/users', async (req, res, next) => {
1143
1290
  export default router;
1144
1291
  ```
1145
1292
 
1293
+ </details>
1294
+
1146
1295
  ## Release Notes
1147
1296
 
1148
1297
  All changes and version history can be found in the [CHANGELOG.md](CHANGELOG.md).
@@ -11,8 +11,8 @@ module.exports = {
11
11
  env_path: '.env',
12
12
 
13
13
  /**
14
- * CORS permission, defaults to invalid (false).
15
- * @type {{enabled: boolean}}
14
+ * CORS permission, defaults to disabled (false).
15
+ * @type {boolean}
16
16
  */
17
17
  cors_enabled: true,
18
18
 
@@ -37,11 +37,12 @@ module.exports = {
37
37
  /**
38
38
  * This is a hook that rewrites the base URL.
39
39
  * If you want to rewrite the app.locals.baseUrl property and the view's baseUrl variable, use this hook to return a new base URL.
40
- * The default value is the referrer's origin (eg https://example.com).
41
- * @type {(baseUrl: string): string}
40
+ * The baseUrl parameter may be undefined if URL construction fails (e.g., invalid Host header).
41
+ * @type {(baseUrl: string | undefined) => string | undefined}
42
42
  * @example
43
43
  * ```js
44
44
  * rewrite_base_url: baseUrl => {
45
+ * if (!baseUrl) return 'http://localhost:3000'; // Fallback for undefined
45
46
  * return `${baseUrl}/admin`;
46
47
  * }
47
48
  * ```
@@ -0,0 +1,91 @@
1
+ /**
2
+ * File upload configuration interface using Multer.
3
+ */
4
+ module.exports = {
5
+ /**
6
+ * Enable file upload middleware, defaults to disabled (false).
7
+ * @type {boolean}
8
+ * @example
9
+ * ```js
10
+ * // Enable file upload middleware
11
+ * enabled: true,
12
+ *
13
+ * // Disable file upload middleware
14
+ * enabled: false,
15
+ * ```
16
+ */
17
+ enabled: false,
18
+
19
+ /**
20
+ * Hook function to dynamically resolve multer middleware based on request.
21
+ * Return a multer middleware instance or null to skip upload handling for the request.
22
+ * @type {(req: express.Request, multer: typeof import('multer')) => Function|null}
23
+ * @example
24
+ * ```js
25
+ * // Single file upload
26
+ * resolve_middleware: (req, multer) => {
27
+ * if (req.path === '/api/user/avatar' && req.method === 'POST') {
28
+ * const upload = multer({ storage: multer.memoryStorage() });
29
+ * return upload.single('avatar');
30
+ * }
31
+ * return null;
32
+ * },
33
+ * ```
34
+ * @example
35
+ * ```js
36
+ * // Multiple files with same field name
37
+ * resolve_middleware: (req, multer) => {
38
+ * if (req.path === '/api/gallery' && req.method === 'POST') {
39
+ * const upload = multer({ storage: multer.memoryStorage() });
40
+ * return upload.array('photos', 10);
41
+ * }
42
+ * return null;
43
+ * },
44
+ * ```
45
+ * @example
46
+ * ```js
47
+ * // Multiple file fields
48
+ * resolve_middleware: (req, multer) => {
49
+ * if (req.path === '/api/admin/firms' && req.method === 'POST') {
50
+ * const upload = multer({ storage: multer.memoryStorage() });
51
+ * return upload.fields([
52
+ * { name: 'logo', maxCount: 1 },
53
+ * { name: 'eyecatch', maxCount: 1 }
54
+ * ]);
55
+ * }
56
+ * return null;
57
+ * },
58
+ * ```
59
+ * @example
60
+ * ```js
61
+ * // With disk storage and file filtering
62
+ * resolve_middleware: (req, multer) => {
63
+ * if (req.path === '/api/documents' && req.method === 'POST') {
64
+ * const storage = multer.diskStorage({
65
+ * destination: (req, file, cb) => {
66
+ * cb(null, 'uploads/');
67
+ * },
68
+ * filename: (req, file, cb) => {
69
+ * cb(null, `${Date.now()}-${file.originalname}`);
70
+ * }
71
+ * });
72
+ * const upload = multer({
73
+ * storage,
74
+ * fileFilter: (req, file, cb) => {
75
+ * // Accept only PDF files
76
+ * if (file.mimetype === 'application/pdf') {
77
+ * cb(null, true);
78
+ * } else {
79
+ * cb(new Error('Only PDF files are allowed'));
80
+ * }
81
+ * },
82
+ * limits: { fileSize: 5 * 1024 * 1024 } // 5MB limit
83
+ * });
84
+ * return upload.single('document');
85
+ * }
86
+ * return null;
87
+ * },
88
+ * ```
89
+ */
90
+ resolve_middleware: undefined
91
+ }
@@ -11,8 +11,8 @@ export default {
11
11
  env_path: '.env',
12
12
 
13
13
  /**
14
- * CORS permission, defaults to invalid (false).
15
- * @type {{enabled: boolean}}
14
+ * CORS permission, defaults to disabled (false).
15
+ * @type {boolean}
16
16
  */
17
17
  cors_enabled: true,
18
18
 
@@ -37,11 +37,12 @@ export default {
37
37
  /**
38
38
  * This is a hook that rewrites the base URL.
39
39
  * If you want to rewrite the app.locals.baseUrl property and the view's baseUrl variable, use this hook to return a new base URL.
40
- * The default value is the referrer's origin (eg https://example.com).
41
- * @type {(baseUrl: string): string}
40
+ * The baseUrl parameter may be undefined if URL construction fails (e.g., invalid Host header).
41
+ * @type {(baseUrl: string | undefined) => string | undefined}
42
42
  * @example
43
43
  * ```js
44
44
  * rewrite_base_url: baseUrl => {
45
+ * if (!baseUrl) return 'http://localhost:3000'; // Fallback for undefined
45
46
  * return `${baseUrl}/admin`;
46
47
  * }
47
48
  * ```
@@ -0,0 +1,91 @@
1
+ /**
2
+ * File upload configuration interface using Multer.
3
+ */
4
+ export default {
5
+ /**
6
+ * Enable file upload middleware, defaults to disabled (false).
7
+ * @type {boolean}
8
+ * @example
9
+ * ```js
10
+ * // Enable file upload middleware
11
+ * enabled: true,
12
+ *
13
+ * // Disable file upload middleware
14
+ * enabled: false,
15
+ * ```
16
+ */
17
+ enabled: false,
18
+
19
+ /**
20
+ * Hook function to dynamically resolve multer middleware based on request.
21
+ * Return a multer middleware instance or null to skip upload handling for the request.
22
+ * @type {(req: express.Request, multer: typeof import('multer')) => Function|null}
23
+ * @example
24
+ * ```js
25
+ * // Single file upload
26
+ * resolve_middleware: (req, multer) => {
27
+ * if (req.path === '/api/user/avatar' && req.method === 'POST') {
28
+ * const upload = multer({ storage: multer.memoryStorage() });
29
+ * return upload.single('avatar');
30
+ * }
31
+ * return null;
32
+ * },
33
+ * ```
34
+ * @example
35
+ * ```js
36
+ * // Multiple files with same field name
37
+ * resolve_middleware: (req, multer) => {
38
+ * if (req.path === '/api/gallery' && req.method === 'POST') {
39
+ * const upload = multer({ storage: multer.memoryStorage() });
40
+ * return upload.array('photos', 10);
41
+ * }
42
+ * return null;
43
+ * },
44
+ * ```
45
+ * @example
46
+ * ```js
47
+ * // Multiple file fields
48
+ * resolve_middleware: (req, multer) => {
49
+ * if (req.path === '/api/admin/firms' && req.method === 'POST') {
50
+ * const upload = multer({ storage: multer.memoryStorage() });
51
+ * return upload.fields([
52
+ * { name: 'logo', maxCount: 1 },
53
+ * { name: 'eyecatch', maxCount: 1 }
54
+ * ]);
55
+ * }
56
+ * return null;
57
+ * },
58
+ * ```
59
+ * @example
60
+ * ```js
61
+ * // With disk storage and file filtering
62
+ * resolve_middleware: (req, multer) => {
63
+ * if (req.path === '/api/documents' && req.method === 'POST') {
64
+ * const storage = multer.diskStorage({
65
+ * destination: (req, file, cb) => {
66
+ * cb(null, 'uploads/');
67
+ * },
68
+ * filename: (req, file, cb) => {
69
+ * cb(null, `${Date.now()}-${file.originalname}`);
70
+ * }
71
+ * });
72
+ * const upload = multer({
73
+ * storage,
74
+ * fileFilter: (req, file, cb) => {
75
+ * // Accept only PDF files
76
+ * if (file.mimetype === 'application/pdf') {
77
+ * cb(null, true);
78
+ * } else {
79
+ * cb(new Error('Only PDF files are allowed'));
80
+ * }
81
+ * },
82
+ * limits: { fileSize: 5 * 1024 * 1024 } // 5MB limit
83
+ * });
84
+ * return upload.single('document');
85
+ * }
86
+ * return null;
87
+ * },
88
+ * ```
89
+ */
90
+ resolve_middleware: undefined
91
+ }