express-sweet 4.0.0 → 5.1.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 (93) hide show
  1. package/CHANGELOG.md +221 -397
  2. package/LICENSE +1 -1
  3. package/README.md +210 -1174
  4. package/dist/build.cjs +32 -73
  5. package/dist/build.mjs +32 -73
  6. package/package.json +45 -61
  7. package/screenshots/avatar.png +0 -0
  8. package/screenshots/edit-profile.png +0 -0
  9. package/screenshots/hero-banner.png +0 -0
  10. package/screenshots/home.png +0 -0
  11. package/screenshots/mount-flow.mmd +11 -0
  12. package/screenshots/mount-flow.png +0 -0
  13. package/screenshots/new-person.png +0 -0
  14. package/screenshots/people.png +0 -0
  15. package/screenshots/sign-in.png +0 -0
  16. package/types/database/DatabaseManager.d.ts +15 -10
  17. package/types/database/Model.d.ts +29 -43
  18. package/types/database/index.d.ts +0 -1
  19. package/types/database/loadModels.d.ts +7 -13
  20. package/types/helpers/array.d.ts +21 -0
  21. package/types/helpers/comparison.d.ts +217 -0
  22. package/types/helpers/date.d.ts +20 -0
  23. package/types/helpers/html.d.ts +35 -0
  24. package/types/{handlebars_helpers → helpers}/index.d.ts +0 -2
  25. package/types/helpers/layouts.d.ts +29 -0
  26. package/types/helpers/math.d.ts +85 -0
  27. package/types/helpers/number.d.ts +19 -0
  28. package/types/helpers/object.d.ts +28 -0
  29. package/types/helpers/string.d.ts +45 -0
  30. package/types/index.d.ts +6 -9
  31. package/types/middleware/auth.d.ts +186 -0
  32. package/types/middleware/cors.d.ts +19 -0
  33. package/types/middleware/env.d.ts +40 -0
  34. package/types/middleware/error.d.ts +26 -0
  35. package/types/middleware/globals.d.ts +13 -0
  36. package/types/{middlewares → middleware}/index.d.ts +12 -13
  37. package/types/middleware/locals.d.ts +33 -0
  38. package/types/middleware/parser.d.ts +30 -0
  39. package/types/middleware/router.d.ts +31 -0
  40. package/types/middleware/views.d.ts +37 -0
  41. package/types/mount.d.ts +2 -3
  42. package/types/{interfaces → types}/AppConfig.d.ts +29 -18
  43. package/types/{interfaces → types}/AuthenticationConfig.d.ts +10 -11
  44. package/types/{interfaces → types}/DatabaseConfig.d.ts +0 -1
  45. package/types/{interfaces → types}/LoggingConfig.d.ts +0 -1
  46. package/types/{interfaces → types}/UploadConfig.d.ts +0 -1
  47. package/types/{interfaces → types}/ViewConfig.d.ts +1 -2
  48. package/types/{interfaces → types}/index.d.ts +1 -2
  49. package/types/utils/index.d.ts +0 -1
  50. package/types/utils/loadAppConfig.d.ts +1 -1
  51. package/types/utils/loadAuthenticationConfig.d.ts +1 -1
  52. package/types/utils/loadLoggingConfig.d.ts +1 -1
  53. package/types/utils/loadUploadConfig.d.ts +1 -1
  54. package/types/utils/loadViewConfig.d.ts +1 -1
  55. package/configuration_sample/cjs/authentication.js +0 -138
  56. package/configuration_sample/cjs/config.js +0 -92
  57. package/configuration_sample/cjs/database.js +0 -121
  58. package/configuration_sample/cjs/logging.js +0 -41
  59. package/configuration_sample/cjs/upload.js +0 -91
  60. package/configuration_sample/cjs/view.js +0 -54
  61. package/configuration_sample/esm/authentication.js +0 -136
  62. package/configuration_sample/esm/config.js +0 -92
  63. package/configuration_sample/esm/database.js +0 -121
  64. package/configuration_sample/esm/logging.js +0 -41
  65. package/configuration_sample/esm/upload.js +0 -91
  66. package/configuration_sample/esm/view.js +0 -54
  67. package/screencaps/belongs-to-many.png +0 -0
  68. package/screencaps/belongs-to.png +0 -0
  69. package/screencaps/demonstration.webp +0 -0
  70. package/screencaps/has-many.png +0 -0
  71. package/screencaps/has-one.png +0 -0
  72. package/types/handlebars_helpers/array.d.ts +0 -22
  73. package/types/handlebars_helpers/comparison.d.ts +0 -222
  74. package/types/handlebars_helpers/date.d.ts +0 -19
  75. package/types/handlebars_helpers/html.d.ts +0 -31
  76. package/types/handlebars_helpers/layouts.d.ts +0 -25
  77. package/types/handlebars_helpers/math.d.ts +0 -74
  78. package/types/handlebars_helpers/number.d.ts +0 -18
  79. package/types/handlebars_helpers/object.d.ts +0 -21
  80. package/types/handlebars_helpers/string.d.ts +0 -45
  81. package/types/middlewares/corsPolicy.d.ts +0 -28
  82. package/types/middlewares/envLoader.d.ts +0 -34
  83. package/types/middlewares/errorHandler.d.ts +0 -32
  84. package/types/middlewares/globalVars.d.ts +0 -25
  85. package/types/middlewares/localVars.d.ts +0 -44
  86. package/types/middlewares/passportAuth.d.ts +0 -15
  87. package/types/middlewares/requestParser.d.ts +0 -27
  88. package/types/middlewares/routeMapper.d.ts +0 -54
  89. package/types/middlewares/viewEngine.d.ts +0 -49
  90. package/types/services/Authentication.d.ts +0 -95
  91. package/types/services/index.d.ts +0 -33
  92. package/types/types/global.d.ts +0 -38
  93. package/types/utils/Types.d.ts +0 -29
package/README.md CHANGED
@@ -1,1309 +1,345 @@
1
- # EXPRESS SWEET
2
-
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
-
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)
1
+ <p align="center">
2
+ <img src="screenshots/hero-banner.png" alt="Express Sweet" width="100%">
3
+ </p>
39
4
 
40
- ## Features
41
-
42
- EXPRESS SWEET provides the following key features to accelerate your development:
43
-
44
- - **Automatic Routing**: Files in the `routes/` directory are automatically mapped to URL endpoints
45
- - **Database ORM**: Built-in Sequelize integration with automatic connection management
46
- - **Authentication**: Passport-based authentication system with session management
47
- - **Template Engine**: Handlebars view engine with custom helpers and layout support
48
- - **Environment Management**: Automatic environment variable loading and configuration
49
- - **Logging**: Morgan-based HTTP request logging with customizable formats
50
- - **CORS Support**: Built-in Cross-Origin Resource Sharing support
51
- - **Project Generator**: Command-line tool to quickly scaffold new applications
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
-
63
- ## API Reference
64
-
65
- **[Complete API Documentation](https://takuya-motoshima.github.io/express-sweet/)**
66
-
67
- The comprehensive API reference includes detailed documentation for:
68
-
69
- - **[Database](https://takuya-motoshima.github.io/express-sweet/modules/database.html)**: `DatabaseManager`, `Model` classes with full Sequelize integration, and `loadModels` utility
70
- - **[Services](https://takuya-motoshima.github.io/express-sweet/modules/services.html)**: `Authentication` service for user login, logout, and session management
71
- - **[Handlebars Helpers](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.html)**: Complete collection of template helpers including:
72
- - **[Array](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.array.html)**: `findObjectInArray`
73
- - **[Comparison](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.comparison.html)**: `eq`, `gt`, `lt`, `and`, `or`, `empty`, `includes`, etc.
74
- - **[String](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.string.html)**: `replace`, `split`, `formatBytes`
75
- - **[Date](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.date.html)**: `formatDate`
76
- - **[Math](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.math.html)**: `add`, `subtract`, `multiply`, `divide`, `ceil`, `floor`, `abs`
77
- - **[Number](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.number.html)**: `number2locale`
78
- - **[Object](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.object.html)**: `jsonStringify`, `jsonParse`
79
- - **[HTML](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.html.html)**: `cacheBusting`, `stripTags`
80
- - **[Layouts](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.layouts.html)**: `block`, `contentFor`
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`
87
- - **[Utilities](https://takuya-motoshima.github.io/express-sweet/modules/utils.html)**: Type checking functions and configuration loaders
88
- - **[Mount Function](https://takuya-motoshima.github.io/express-sweet/variables/mount.html)**: Application initialization and setup
89
-
90
- ## EXPRESS SWEET Generator
91
-
92
- Use the application generator tool, `express-sweet-generator`, to quickly create an application skeleton.
93
-
94
- ![Image](screencaps/demonstration.webp)
95
-
96
- 1. **Install the generator globally** as an npm package:
97
- ```bash
98
- npm install -g express-sweet-generator
99
- ```
100
-
101
- 2. **Display command options** with the `-h` flag:
102
- ```bash
103
- express-sweet -h
104
-
105
- Usage: express-sweet [options] [dir]
106
-
107
- Options:
108
- --version output the version number
109
- -o, --output <output> add output <module> support (esm|cjs) (defaults to cjs)
110
- -p, --port <port> application listening port (default: 3000)
111
- -f, --force force on non-empty directory
112
- -h, --help output usage information
113
- ```
114
-
115
- 3. **Create your application**. For example, the following creates an Express app named `myapp` using ESM modules:
116
- ```bash
117
- express-sweet -o esm myapp
118
- ```
119
-
120
- 4. **Install dependencies** and start developing:
121
- ```bash
122
- cd myapp/
123
- npm install
124
- ```
125
-
126
- <details>
127
- <summary><strong>Quick Start</strong></summary>
5
+ <p align="center">
6
+ <a href="https://www.npmjs.com/package/express-sweet"><img src="https://img.shields.io/npm/v/express-sweet" alt="npm"></a>
7
+ <a href="LICENSE"><img src="https://img.shields.io/npm/l/express-sweet" alt="license"></a>
8
+ <a href="package.json"><img src="https://img.shields.io/node/v/express-sweet" alt="node"></a>
9
+ </p>
128
10
 
129
- ## Quick Start
130
-
131
- ### Database Setup
132
-
133
- The application skeleton uses a MySQL/MariaDB database. Create a database with the following SQL:
134
-
135
- ```sql
136
- -- Create database
137
- CREATE DATABASE IF NOT EXISTS `sample_db` DEFAULT CHARACTER SET utf8mb4;
138
-
139
- USE `sample_db`;
140
-
141
- -- User table: Stores user account information
142
- CREATE TABLE `user` (
143
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
144
- `name` varchar(30) NOT NULL COMMENT 'User display name',
145
- `email` varchar(255) NOT NULL COMMENT 'User email address (unique)',
146
- `password` varchar(100) NOT NULL COMMENT 'Encrypted password',
147
- `icon` varchar(768) NOT NULL DEFAULT MD5(RAND()) COMMENT 'User icon path or identifier',
148
- `created` datetime NOT NULL DEFAULT current_timestamp() COMMENT 'Record creation timestamp',
149
- `modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT 'Record last modified timestamp',
150
- PRIMARY KEY (`id`),
151
- UNIQUE KEY `ukUserEmail` (`email`),
152
- UNIQUE KEY `ukUserIcon`(`icon`)
153
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='User accounts table';
154
-
155
- -- Profile table: Stores additional user profile information
156
- CREATE TABLE `profile` (
157
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
158
- `userId` int(10) unsigned NOT NULL COMMENT 'Foreign key to user table',
159
- `address` varchar(255) NOT NULL COMMENT 'User address',
160
- `tel` varchar(14) NOT NULL COMMENT 'User telephone number',
161
- `created` datetime NOT NULL DEFAULT current_timestamp() COMMENT 'Record creation timestamp',
162
- `modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT 'Record last modified timestamp',
163
- PRIMARY KEY (`id`),
164
- UNIQUE KEY `ukProfileUserId` (`userId`),
165
- CONSTRAINT `fkProfileUser` FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE CASCADE
166
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='User profiles table';
167
-
168
- -- Comment table: Stores user comments
169
- CREATE TABLE `comment` (
170
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
171
- `userId` int(10) unsigned NOT NULL COMMENT 'Foreign key to user table',
172
- `text` text NOT NULL COMMENT 'Comment text content',
173
- `created` datetime NOT NULL DEFAULT current_timestamp() COMMENT 'Record creation timestamp',
174
- `modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT 'Record last modified timestamp',
175
- PRIMARY KEY (`id`),
176
- CONSTRAINT `fkCommentUser` FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE CASCADE
177
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='User comments table';
178
-
179
- -- Book table: Stores user books
180
- CREATE TABLE `book` (
181
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
182
- `userId` int(10) unsigned NOT NULL COMMENT 'Foreign key to user table',
183
- `title` text NOT NULL COMMENT 'Book title',
184
- `created` datetime NOT NULL DEFAULT current_timestamp() COMMENT 'Record creation timestamp',
185
- `modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT 'Record last modified timestamp',
186
- PRIMARY KEY (`id`),
187
- UNIQUE KEY `ukBookTitle` (`userId`, `title`(255)),
188
- CONSTRAINT `fkBookUser` FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE CASCADE
189
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='User books table';
190
-
191
- -- Sample data insertion
192
- INSERT INTO `user` (`id`, `email`, `password`, `name`, `icon`) VALUES
193
- (1, 'robin@example.com', 'password', 'Robin', '/upload/1.png'),
194
- (2, 'taylor@example.com', 'password', 'Taylor', '/upload/2.png');
195
-
196
- INSERT INTO `profile` (`userId`, `address`, `tel`) VALUES
197
- (1, '777 Brockton Avenue, Abington MA 2351', '202-555-0105'),
198
- (2, '30 Memorial Drive, Avon MA 2322', '');
199
-
200
- INSERT INTO `comment` (`userId`, `text`) VALUES
201
- (1, 'From Robin #1'),
202
- (1, 'From Robin #2'),
203
- (2, 'From Taylor #1');
204
-
205
- INSERT INTO `book` (`userId`, `title`) VALUES
206
- (1, 'Beautiful'),
207
- (1, 'Lose Yourself'),
208
- (2, 'When Im Gone');
209
- ```
11
+ One function call. Full stack. Auth, ORM, routing, views — everything snaps together so you can ship fast and stay sharp.
210
12
 
211
- ### Database Configuration
13
+ ## What is Express Sweet?
212
14
 
213
- Configure the database connection in `config/database.js`. For detailed options, refer to the [Sequelize documentation](https://sequelize.org/docs/v6/other-topics/migrations/#cfg).
15
+ Express Sweet is a full-stack toolkit built on top of Express.js. Instead of wiring up a dozen middleware packages by hand, you call one function and get a production-ready stack: Sequelize ORM, Passport.js authentication, Handlebars views with 37 built-in helpers, file-based routing, file uploads, and more.
214
16
 
215
17
  ```js
216
- export default {
217
- development: {
218
- username: 'root',
219
- password: 'password',
220
- database: 'sample_db',
221
- host: 'localhost',
222
- dialect: 'mariadb'
223
- },
224
- test: {
225
- username: 'root',
226
- password: 'password',
227
- database: 'sample_db',
228
- host: 'localhost',
229
- dialect: 'mariadb'
230
- },
231
- production: {
232
- username: 'root',
233
- password: 'password',
234
- database: 'sample_db',
235
- host: 'localhost',
236
- dialect: 'mariadb'
237
- }
238
- }
239
- ```
240
-
241
- ### Environment Configuration
242
-
243
- The database environment can be defined for each deployment stage. Specify the environment in the `.env` file:
18
+ import express from 'express';
19
+ import * as expx from 'express-sweet';
244
20
 
245
- ```bash
246
- NODE_ENV=development
21
+ const app = express();
22
+ await expx.mount(app);
23
+ app.listen(3000);
247
24
  ```
248
25
 
249
- ### Running the Application
26
+ That's it. Four lines of real code and you have a fully configured web application.
250
27
 
251
- Start the application with the following command:
28
+ ## Features
252
29
 
253
- ```bash
254
- npm start
255
- ```
30
+ - **One-line setup** — `expx.mount(app)` initializes everything in the right order
31
+ - **File-based routing** — Drop a file in `routes/`, get a URL endpoint automatically
32
+ - **Sequelize ORM** — Custom `Model` base class with `findById()`, `begin()`, raw queries, and association support
33
+ - **Passport.js auth** — Username/password login, session management (memory or Redis), route protection
34
+ - **Handlebars views** — Pre-configured template engine with 37 built-in helpers
35
+ - **File uploads** — Multer integration with per-route upload resolution
36
+ - **CORS** — Toggle with a single config flag
37
+ - **Environment variables** — Automatic `.env` loading, plus a post-load hook for decrypting secrets or validating required values
38
+ - **Dual format** — Ships as both ESM and CommonJS
256
39
 
257
- Then open `http://localhost:3000/` in your browser to access the application.
40
+ ## Screenshots
258
41
 
259
- </details>
42
+ | Sign In | Home | People |
43
+ |---------|------|--------|
44
+ | ![Sign In](screenshots/sign-in.png) | ![Home](screenshots/home.png) | ![People](screenshots/people.png) |
260
45
 
261
- <details>
262
- <summary><strong>Project Structure</strong></summary>
46
+ | New Person | Edit Profile | Change Avatar |
47
+ |------------|-------------|---------------|
48
+ | ![New Person](screenshots/new-person.png) | ![Edit Profile](screenshots/edit-profile.png) | ![Avatar](screenshots/avatar.png) |
263
49
 
264
- ## Project Structure
50
+ ## Quick Start
265
51
 
266
- The generated application has the following directory structure:
52
+ ### The fast way — use the generator
267
53
 
268
54
  ```bash
269
- .
270
- ├── .env # Environment variables configuration
271
- ├── app.js # Main application entry point
272
- ├── ecosystem.config.js # PM2 process manager configuration
273
- ├── nginx.sample.conf # Sample Nginx reverse proxy configuration
274
- ├── package.json # Node.js dependencies and scripts
275
- ├── bin
276
- │ └── www # Application startup script
277
- ├── client # Frontend application directory
278
- │ ├── package.json # Frontend dependencies
279
- │ ├── webpack.config.js # Webpack bundler configuration
280
- │ └── src # Frontend source code
281
- ├── config # Application configuration files
282
- │ ├── authentication.js # Authentication and session settings
283
- │ ├── config.js # Core application configuration
284
- │ ├── database.js # Database connection settings
285
- │ ├── logging.js # HTTP request logging configuration
286
- │ ├── upload.js # File upload configuration
287
- │ └── view.js # Template engine configuration
288
- ├── errors # Custom error classes
289
- │ └── UserNotFound.js # Custom error definitions
290
- ├── models # Database models (Sequelize ORM)
291
- │ ├── BookModel.js # Book entity model
292
- │ ├── CommentModel.js # Comment entity model
293
- │ ├── ProfileModel.js # User profile model
294
- │ └── UserModel.js # User entity model
295
- ├── public # Static assets directory
296
- │ ├── build # Compiled frontend assets
297
- │ └── upload # User uploaded files
298
- ├── routes # Express route definitions
299
- │ ├── login.js # Authentication routes
300
- │ ├── users.js # User management routes
301
- │ └── api # API endpoints
302
- │ └── users.js # User API routes
303
- ├── shared # Shared utilities and helpers
304
- │ ├── CustomValidation.js # Custom validation functions
305
- │ └── empty.js # Utility functions
306
- └── views # Handlebars template files
307
- ├── edit-personal.hbs # Profile editing template
308
- ├── error.hbs # Error page template
309
- ├── login.hbs # Login page template
310
- ├── personal.hbs # Profile display template
311
- ├── users.hbs # Users listing template
312
- ├── layout # Layout templates
313
- │ └── default.hbs # Default page layout
314
- └── partials # Reusable template components
315
- └── .gitkeep # Placeholder for partial templates
316
- ```
317
-
318
- ### Key Directories Explained
319
-
320
- **Configuration (`config/`)**
321
- Contains all application settings divided by functionality. Modify these files to customize database connections, authentication behavior, view rendering, and logging.
322
-
323
- **Models (`models/`)**
324
- Database entities using Sequelize ORM. Each model represents a database table and defines the schema, relationships, and business logic for that entity.
325
-
326
- **Routes (`routes/`)**
327
- URL endpoint handlers organized by feature. The file structure automatically maps to URL paths - for example, `routes/api/users.js` handles requests to `/api/users`.
328
-
329
- **Views (`views/`)**
330
- Handlebars templates for rendering HTML pages. The `layout/` directory contains base templates, while `partials/` holds reusable components.
331
-
332
- **Public (`public/`)**
333
- Static files served directly by the web server. The `build/` directory contains compiled frontend assets, while `upload/` stores user-generated content.
334
-
335
- </details>
336
-
337
- <details>
338
- <summary><strong>Configuration</strong></summary>
339
-
340
- ## Configuration
341
-
342
- EXPRESS SWEET uses several configuration files to customize application behavior. Each configuration file corresponds to a specific aspect of the framework:
343
-
344
- ### Environment Variables
345
-
346
- If you set the environment variable file in `env_path` of `config/config.js`, the values will be automatically loaded into `process.env`.
347
-
348
- The `NODE_ENV` environment variable is required. If omitted, `development` is used by default.
349
-
350
- You can access environment variables and perform custom logic as needed:
351
- ```js
352
- if (process.env.NODE_ENV === 'development') {
353
- // Development-specific logic
354
- }
55
+ npx express-sweet myapp
56
+ cd myapp
57
+ npm install
58
+ npm run setup
59
+ npm start
355
60
  ```
356
61
 
357
- ### Base Configuration (`config/config.js`)
358
-
359
- The core configuration of EXPRESS SWEET is defined in the `config/config.js` file.
360
-
361
- **Sample configurations:**
362
- - [ESM Configuration](configuration_sample/esm/config.js)
363
- - [CJS Configuration](configuration_sample/cjs/config.js)
364
-
365
- **Configuration Options:**
366
-
367
- - **`env_path: string`**
368
- Environment variable file (`.env`) path. Defaults to `undefined`.
369
- When the EXPRESS SWEET application starts, the environment file contents are automatically loaded into `process.env`.
370
-
371
- - **`cors_enabled: boolean`**
372
- Enable CORS (Cross-Origin Resource Sharing). Defaults to `false`.
373
- Set to `true` to allow requests from other domains.
374
-
375
- - **`max_body_size: string|number`**
376
- Maximum request body size. Defaults to `100kb`.
377
- If a number, specifies bytes. If a string, parsed by the [bytes library](https://www.npmjs.com/package/bytes).
378
-
379
- - **`router_dir: string`**
380
- Absolute path to the router directory. Defaults to `<application root>/routes`.
381
-
382
- - **`default_router: string`**
383
- Endpoint to run when the root URL is requested. Defaults to `undefined`.
384
- EXPRESS SWEET can load a default router when no URI is present (root URL `/` requests).
385
-
386
- - **`rewrite_base_url: (baseUrl: string) => string`**
387
- Hook to rewrite the base URL for `app.locals.baseUrl` and view's `baseUrl` variable.
388
- Default value is the referrer's origin (e.g., `https://example.com`).
389
-
390
- - **`is_ajax: (req: express.Request) => boolean`**
391
- Custom logic to determine Ajax requests.
392
- Defaults to checking for XMLHttpRequest in headers (`req.xhr`).
393
-
394
- - **`hook_handle_error: (error: any, req: express.Request, res: express.Response, next: express.NextFunction) => void`**
395
- Custom error handling hook. If unset, returns appropriate HTTP status codes.
396
-
397
- ### Database Configuration (`config/database.js`)
398
-
399
- Database settings are defined in the `config/database.js` file.
400
-
401
- **Sample configurations:**
402
- - [ESM Configuration](configuration_sample/esm/database.js)
403
- - [CJS Configuration](configuration_sample/cjs/database.js)
404
-
405
- **Configuration Options:**
406
-
407
- - **`username: string`** - Database authentication username
408
- - **`password: string|null`** - Database authentication password (default: `null`)
409
- - **`database: string`** - Database name
410
- - **`host: string`** - Database host
411
- - **`port: number|null`** - Database port (default: auto-select)
412
- - **`dialect: string`** - Database dialect: `mariadb`, `mysql`, `postgres`, `sqlite`, or `mssql`
413
- - **`logging: boolean|(...message: any[]) => void`** - Query logging (default: `false`)
414
- - **`timezone: string`** - Database timezone (e.g., `'+09:00'` for JST)
415
-
416
- ### Authentication Configuration (`config/authentication.js`)
417
-
418
- User authentication settings are defined in the `config/authentication.js` file.
62
+ One command scaffolds a complete app with auth, database, CRUD, and file uploads — ready to run. See [express-sweet-generator](https://github.com/shumatsumonobu/express-sweet-generator) for options.
419
63
 
420
- **Sample configurations:**
421
- - [ESM Configuration](configuration_sample/esm/authentication.js)
422
- - [CJS Configuration](configuration_sample/cjs/authentication.js)
64
+ ### From scratch
423
65
 
424
- ### View Configuration (`config/view.js`)
425
-
426
- Template engine settings are defined in the `config/view.js` file.
427
-
428
- **Sample configurations:**
429
- - [ESM Configuration](configuration_sample/esm/view.js)
430
- - [CJS Configuration](configuration_sample/cjs/view.js)
431
-
432
- ### Logging Configuration (`config/logging.js`)
433
-
434
- HTTP request logging settings are defined in the `config/logging.js` file.
435
-
436
- **Sample configurations:**
437
- - [ESM Configuration](configuration_sample/esm/logging.js)
438
- - [CJS Configuration](configuration_sample/cjs/logging.js)
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
- }
66
+ #### Install
474
67
 
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
- }
68
+ ```bash
69
+ npm install express-sweet
495
70
  ```
496
71
 
497
- **Accessing Uploaded Files in Routes:**
498
-
499
- ```js
500
- import {Router} from 'express';
501
-
502
- const router = Router();
72
+ #### Create config files
503
73
 
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
- });
74
+ Express Sweet uses convention-based configuration. Create a `config/` directory with the files you need:
532
75
 
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
76
  ```
552
-
553
- </details>
554
-
555
- <details>
556
- <summary><strong>Routing</strong></summary>
557
-
558
- ## Routing
559
-
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.).
561
-
562
- ### Basic Routing
563
-
564
- All routes are defined in route files located in the `routes/` directory. These files are automatically mapped by EXPRESS SWEET to URL endpoints based on their file paths.
565
-
566
- **Example:** `routes/user.js` responds to `GET /user` requests:
567
- ```js
568
- import {Router} from 'express';
569
-
570
- const router = Router();
571
- router.get('/', (req, res) => {
572
- res.send('Hello World');
573
- });
574
-
575
- export default router;
77
+ your-app/
78
+ config/
79
+ config.js # App basics (CORS, body size, routing)
80
+ database.js # Sequelize connection settings
81
+ authentication.js # Passport.js auth settings (optional)
82
+ view.js # Handlebars view engine (optional)
83
+ logging.js # Morgan HTTP logging (optional)
84
+ upload.js # Multer file upload (optional)
85
+ routes/
86
+ home.js # → /home
87
+ api/
88
+ users.js # → /api/users
89
+ models/
90
+ UserModel.js
91
+ views/
92
+ home.hbs
93
+ app.js
576
94
  ```
577
95
 
578
- ### Nested Routing
96
+ You don't need to write config files from scratch. Copy from [examples/](examples/) (ESM and CJS templates included) and just fill in your values.
579
97
 
580
- The router supports nested folder structures. Nested files are automatically routed following the same path convention.
98
+ #### Boot the app
581
99
 
582
- **Example:** `routes/api/users.js` responds to `GET /api/users` requests:
583
100
  ```js
584
- import {Router} from 'express';
585
-
586
- const router = Router();
587
- router.get('/', (req, res) => {
588
- res.send('Hello World');
589
- });
590
-
591
- export default router;
592
- ```
593
-
594
- ### Default Routing
595
-
596
- EXPRESS SWEET can load a default router when no URI is present (root URL `/` requests). To specify a default router, set `default_router` in your `config/config.js` file:
101
+ // app.js (ESM)
102
+ import express from 'express';
103
+ import * as expx from 'express-sweet';
597
104
 
598
- ```js
599
- default_router: '/blog'
105
+ const app = express();
106
+ await expx.mount(app);
107
+ app.listen(3000, () => console.log('Running on http://localhost:3000'));
600
108
  ```
601
109
 
602
- Where `blog` corresponds to the router module name. Create the corresponding `routes/blog.js` module:
603
-
604
110
  ```js
605
- import {Router} from 'express';
606
-
607
- const router = Router();
608
- router.get('/', (req, res) => {
609
- res.send('Hello World');
610
- });
611
-
612
- export default router;
111
+ // app.js (CommonJS)
112
+ const express = require('express');
113
+ const expx = require('express-sweet');
114
+
115
+ async function main() {
116
+ const app = express();
117
+ await expx.mount(app);
118
+ app.listen(3000, () => console.log('Running on http://localhost:3000'));
119
+ }
120
+ main();
613
121
  ```
614
122
 
615
- Now when you request the root URL (`/`), you will see "Hello World".
123
+ `mount()` initializes all middleware in a carefully ordered sequence:
616
124
 
617
- ### Routing Methods
125
+ <!-- Mermaid source: screenshots/mount-flow.mmd, regenerate with: npm run diagram -->
126
+ ![mount flow](screenshots/mount-flow.png)
618
127
 
619
- Express supports routing methods corresponding to HTTP methods:
620
-
621
- - `checkout`, `copy`, `delete`, `get`, `head`, `lock`, `merge`, `mkactivity`, `mkcol`, `move`, `m-search`, `notify`, `options`, `patch`, `post`, `purge`, `put`, `report`, `search`, `subscribe`, `trace`, `unlock`, `unsubscribe`
622
-
623
- For comprehensive routing documentation, see the [Express Routing Guide](https://expressjs.com/en/guide/routing.html#express-router).
624
-
625
- </details>
626
-
627
- <details>
628
- <summary><strong>Model</strong></summary>
629
-
630
- ## Model
631
-
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:
633
-
634
- - **Automatic database connection management**
635
- - **Built-in CRUD methods**
636
- - **Query builder integration**
637
- - **Model relationships and associations**
638
- - **Data validation and hooks**
639
-
640
- This base class provides a solid foundation for building your application's model layer, allowing you to rapidly develop database interactions with minimal boilerplate code.
641
-
642
- ### Accessing Models
643
-
644
- Place your model files in the `models/` directory of your application root. Once loaded, you have immediate access to all model functions for database operations.
645
-
646
- **Basic model usage:**
647
- ```js
648
- import BookModel from '../models/BookModel.js';
649
-
650
- // Create a new record
651
- // SQL: INSERT INTO book (title, userId) VALUES ('Beautiful', 1)
652
- await BookModel.create({
653
- title: 'Beautiful',
654
- userId: 1
655
- });
128
+ ## Configuration
656
129
 
657
- // Find all records
658
- // SQL: SELECT * FROM book
659
- const allBooks = await BookModel.findAll();
130
+ Six config files control the framework. All are optional — Express Sweet uses sensible defaults when a file is missing.
660
131
 
661
- // Find with conditions
662
- // SQL: SELECT * FROM book WHERE userId = 1
663
- const userBooks = await BookModel.findAll({
664
- where: { userId: 1 }
665
- });
132
+ | File | Purpose | Key Options |
133
+ |------|---------|-------------|
134
+ | `config.js` | App basics | `cors_enabled`, `max_body_size`, `router_dir`, `default_router`, `hook_after_env_load`, `hook_handle_error` |
135
+ | `database.js` | DB connection | `database`, `username`, `password`, `host`, `dialect`, `pool` |
136
+ | `authentication.js` | Auth settings | `enabled`, `session_store`, `authenticate_user`, `allow_unauthenticated` |
137
+ | `view.js` | View engine | `views_dir`, `partials_dir`, `default_layout`, `beforeRender` |
138
+ | `logging.js` | HTTP logging | `format`, `skip` |
139
+ | `upload.js` | File uploads | `enabled`, `resolve_middleware` |
666
140
 
667
- // Update records
668
- // SQL: UPDATE book SET title = 'Beautiful' WHERE id = 1
669
- await BookModel.update(
670
- { title: 'Beautiful' },
671
- { where: { id: 1 } }
672
- );
673
-
674
- // Delete records
675
- // SQL: DELETE FROM book WHERE id = 1
676
- await BookModel.destroy({
677
- where: { id: 1 }
678
- });
141
+ Full option reference → [docs/configuration.md](docs/configuration.md)
679
142
 
680
- // Find single record
681
- // SQL: SELECT * FROM book WHERE title = 'Beautiful' LIMIT 1
682
- const book = await BookModel.findOne({
683
- where: { title: 'Beautiful' }
684
- });
685
- ```
143
+ ## Database & Models
686
144
 
687
- ### Creating Custom Models
145
+ Express Sweet wraps Sequelize with a `Model` base class and a `DatabaseManager` singleton.
688
146
 
689
- To leverage EXPRESS SWEET's model capabilities, create a new model class that extends `database.Model`. This provides convenient access to the database connection, query builder, and additional utility methods.
147
+ ### Define a model
690
148
 
691
- **Basic model structure:**
692
149
  ```js
150
+ // models/UserModel.js
693
151
  import * as expx from 'express-sweet';
694
152
 
695
- export default class UserModel extends expx.database.Model {
153
+ export default class extends expx.database.Model {
696
154
  static get table() {
697
155
  return 'user';
698
156
  }
699
157
 
700
158
  static get attributes() {
701
159
  return {
702
- id: {
703
- type: this.DataTypes.INTEGER,
704
- primaryKey: true,
705
- autoIncrement: true
706
- },
707
- name: this.DataTypes.STRING,
160
+ id: { type: this.DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
161
+ name: this.DataTypes.STRING,
708
162
  email: this.DataTypes.STRING,
709
- password: this.DataTypes.STRING,
710
- created: this.DataTypes.DATE,
711
- modified: this.DataTypes.DATE
712
163
  };
713
164
  }
714
165
  }
715
166
  ```
716
167
 
717
- ### Model Relationships
718
-
719
- EXPRESS SWEET supports Sequelize associations for building data relationships:
168
+ ### CRUD
720
169
 
721
170
  ```js
722
- // Define associations in your model
723
- static associate(models) {
724
- // One-to-One: User has one Profile
725
- this.hasOne(models.ProfileModel, {
726
- foreignKey: 'userId'
727
- });
728
-
729
- // One-to-Many: User has many Books
730
- this.hasMany(models.BookModel, {
731
- foreignKey: 'userId'
732
- });
733
- }
734
- ```
735
-
736
- For comprehensive model documentation and advanced features, see the [Model API Reference](https://takuya-motoshima.github.io/express-sweet/modules/database.html).
737
-
738
- </details>
739
-
740
- <details>
741
- <summary><strong>View System</strong></summary>
742
-
743
- ## View System
744
-
745
- EXPRESS SWEET uses Handlebars as its template engine with automatic layout support and a rich set of custom helpers.
746
-
747
- ### Layout Usage
748
-
749
- There are three ways to specify a layout, listed in order of precedence:
750
-
751
- 1. **Declarative within a page** using Handlebars comments:
752
- ```handlebars
753
- {{!< LAYOUT}}
754
- ```
755
-
756
- 2. **As an option to render**:
757
- ```js
758
- res.render('veggies', {
759
- title: 'My favorite veggies',
760
- veggies: veggies,
761
- layout: 'layout/veggie'
762
- });
763
- ```
764
-
765
- To suppress layout rendering:
766
- ```js
767
- res.render('veggies', {
768
- title: 'My favorite veggies',
769
- veggies: veggies,
770
- layout: null // render without using a layout template
771
- });
772
- ```
773
-
774
- 3. **Default layout** using `default_layout` specified in view configuration.
775
-
776
- ### Template Syntax
777
-
778
- **Mark where layout should insert page content:**
779
- ```handlebars
780
- {{{body}}}
781
- ```
782
-
783
- **Declare a block placeholder in layout:**
784
- ```handlebars
785
- {{{block "script"}}}
786
- ```
787
-
788
- **Define block content in a page:**
789
- ```handlebars
790
- {{#contentFor "script"}}
791
- <script src="/js/page-specific.js"></script>
792
- {{/contentFor}}
793
- ```
794
-
795
- ### Handlebars Helpers
796
-
797
- EXPRESS SWEET provides a comprehensive collection of custom helpers for common template operations:
798
-
799
- #### Array Helpers
800
-
801
- Work with arrays and objects within arrays:
802
-
803
- ```handlebars
804
- {{!-- Find object in array by property --}}
805
- {{#each items}}
806
- {{#if (eq id 123)}}
807
- {{lookup (findObjectInArray ../items 'id' id) 'name'}}
808
- {{/if}}
809
- {{/each}}
810
- ```
811
-
812
- #### Comparison Helpers
813
-
814
- Perform logical and comparison operations:
815
-
816
- ```handlebars
817
- {{!-- Equality checks --}}
818
- {{#if (eq status 'active')}}Active User{{/if}}
819
-
820
- {{!-- Numerical comparisons --}}
821
- {{#if (gt score 90)}}Excellent Score{{/if}}
822
- {{#if (lt age 18)}}Minor{{/if}}
823
-
824
- {{!-- Logical operations --}}
825
- {{#if (and isLoggedIn hasPermission)}}Show Protected Content{{/if}}
826
- {{#if (or isAdmin isModerator)}}Show Admin Controls{{/if}}
827
-
828
- {{!-- Empty/existence checks --}}
829
- {{#if (empty comments)}}No comments yet{{/if}}
830
- {{#if (includes roles 'admin')}}Admin Access{{/if}}
831
- ```
832
-
833
- #### HTML Helpers
834
-
835
- HTML and asset management utilities:
836
-
837
- ```handlebars
838
- {{!-- Cache busting for static assets --}}
839
- <link rel="stylesheet" href="{{cacheBusting '/css/style.css'}}">
840
- <script src="{{cacheBusting '/js/app.js'}}"></script>
841
-
842
- {{!-- Strip HTML tags from content --}}
843
- {{{stripTags '<p>Hello <strong>World</strong></p>'}}} {{!-- Results: Hello World --}}
844
- ```
845
-
846
- #### Object Helpers
847
-
848
- JSON serialization and parsing:
849
-
850
- ```handlebars
851
- {{!-- Convert objects to JSON strings --}}
852
- <script>
853
- var userData = {{{jsonStringify user}}};
854
- var config = {{{jsonStringify appConfig}}};
855
- </script>
856
-
857
- {{!-- Parse JSON strings back to objects --}}
858
- {{#with (jsonParse jsonString)}}
859
- <h1>{{name}}</h1>
860
- <p>{{email}}</p>
861
- {{/with}}
862
- ```
863
-
864
- #### String Helpers
865
-
866
- String manipulation and formatting:
867
-
868
- ```handlebars
869
- {{!-- String replacement --}}
870
- <h1>{{replace title 'Draft' 'Published'}}</h1>
871
-
872
- {{!-- Split strings into arrays --}}
873
- {{#each (split tags ',')}}
874
- <span class="tag">{{trim this}}</span>
875
- {{/each}}
876
-
877
- {{!-- Format file sizes --}}
878
- <p>File size: {{formatBytes fileSize 2}}</p>
879
- {{!-- Example output: File size: 1.23 MB --}}
880
- ```
881
-
882
- #### Date Helpers
883
-
884
- Date and time formatting with internationalization support:
885
-
886
- ```handlebars
887
- {{!-- Format dates with custom patterns --}}
888
- <p>Created: {{formatDate 'YYYY/MM/DD' createdAt}}</p>
889
- <p>Time: {{formatDate 'HH:mm:ss' timestamp}}</p>
890
-
891
- {{!-- Localized date formatting --}}
892
- <p>Date: {{formatDate 'MMMM Do, YYYY' publishedAt 'en-US'}}</p>
893
- <p>日付: {{formatDate 'YYYY年MM月DD日' publishedAt 'ja-JP'}}</p>
894
- ```
895
-
896
- #### Number Helpers
897
-
898
- Number formatting with locale support:
171
+ import UserModel from '../models/UserModel.js';
899
172
 
900
- ```handlebars
901
- {{!-- Localized number formatting --}}
902
- <p>Price: ${{number2locale price 'en-US'}}</p>
903
- <p>Total: €{{number2locale total 'de-DE'}}</p>
904
- <p>Count: {{number2locale userCount 'ja-JP'}}</p>
173
+ await UserModel.create({ name: 'Alice', email: 'alice@example.com' });
174
+ const users = await UserModel.findAll();
175
+ const user = await UserModel.findById(1);
176
+ await UserModel.update({ name: 'Bob' }, { where: { id: 1 } });
177
+ await UserModel.destroy({ where: { id: 1 } });
905
178
  ```
906
179
 
907
- #### Math Helpers
908
-
909
- Mathematical operations for template calculations:
180
+ ### Transactions
910
181
 
911
- ```handlebars
912
- {{!-- Basic arithmetic --}}
913
- <p>Total: ${{add price tax}}</p>
914
- <p>Discount: ${{subtract price discount}}</p>
915
- <p>Amount: ${{multiply quantity unitPrice}}</p>
916
- <p>Average: {{divide total count}}</p>
917
-
918
- {{!-- Rounding functions --}}
919
- <p>Rounded up: {{ceil 4.3}}</p> {{!-- Results: 5 --}}
920
- <p>Rounded down: {{floor 4.7}}</p> {{!-- Results: 4 --}}
921
- <p>Absolute value: {{abs -15}}</p> {{!-- Results: 15 --}}
182
+ ```js
183
+ let transaction;
184
+ try {
185
+ transaction = await UserModel.begin();
186
+ await UserModel.create({ name: 'Alice' }, { transaction });
187
+ await transaction.commit();
188
+ } catch {
189
+ if (transaction) await transaction.rollback();
190
+ }
922
191
  ```
923
192
 
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).
925
-
926
- </details>
927
-
928
- <details>
929
- <summary><strong>Authentication</strong></summary>
193
+ Full reference (associations, raw queries, operators) → [docs/database.md](docs/database.md)
930
194
 
931
195
  ## Authentication
932
196
 
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.
934
-
935
- **Note:** If an unauthenticated user requests a URL that requires authentication, they will be redirected to the page specified by `failure_redirect`. For asynchronous requests, a `401` error is returned.
197
+ Passport.js integration with session management and automatic route protection.
936
198
 
937
- ### Login Example
938
-
939
- #### Asynchronous Login (Ajax)
940
-
941
- Returns the authentication result for frontend processing:
199
+ ### Config
942
200
 
943
201
  ```js
944
- import {Router} from 'express';
945
- import * as expx from 'express-sweet';
946
-
947
- const router = Router();
948
- router.post('/login', async (req, res, next) => {
949
- const isAuthenticated = await expx.services.Authentication.authenticate(req, res, next);
950
- res.json(isAuthenticated);
951
- });
952
-
953
- export default router;
954
- ```
955
-
956
- **Frontend HTML example:**
957
- ```html
958
- <form id="loginForm">
959
- <label>Email</label>
960
- <input type="email" name="email" required autofocus>
961
- <label>Password</label>
962
- <input type="password" name="password" required>
963
- <button type="submit">Login</button>
964
- </form>
965
-
966
- <script>
967
- const form = document.querySelector('#loginForm');
968
- form.addEventListener('submit', async event => {
969
- event.preventDefault();
970
-
971
- const res = await fetch('/api/users/login', {
972
- method: 'POST',
973
- body: new FormData(form)
974
- });
975
-
976
- const isAuthenticated = await res.json();
977
- if (!isAuthenticated) {
978
- alert('The username or password is incorrect.');
979
- return;
980
- }
981
-
982
- location.href = '/dashboard';
983
- });
984
- </script>
202
+ // config/authentication.js
203
+ export default {
204
+ enabled: true,
205
+ session_store: 'memory', // or 'redis'
206
+ username: 'email',
207
+ password: 'password',
208
+ success_redirect: '/',
209
+ failure_redirect: '/login',
210
+ authenticate_user: async (username, password, req) => {
211
+ return UserModel.findOne({ where: { email: username, password }, raw: true });
212
+ },
213
+ subscribe_user: async (id) => {
214
+ return UserModel.findOne({ where: { id }, raw: true });
215
+ },
216
+ allow_unauthenticated: ['/login', '/api/login'],
217
+ expiration: 24 * 3600000,
218
+ };
985
219
  ```
986
220
 
987
- #### Synchronous Login (Form Submit)
988
-
989
- Redirects based on authentication result:
221
+ ### Login / Logout
990
222
 
991
223
  ```js
992
- import {Router} from 'express';
224
+ import { Router } from 'express';
993
225
  import * as expx from 'express-sweet';
994
226
 
995
227
  const router = Router();
996
- router.post('/login', async (req, res, next) => {
997
- const isAuthenticated = await expx.services.Authentication.authenticate(req, res, next);
998
-
999
- if (isAuthenticated) {
1000
- await expx.services.Authentication.successRedirect(res);
1001
- } else {
1002
- await expx.services.Authentication.failureRedirect(req, res);
1003
- }
1004
- });
1005
228
 
1006
- export default router;
1007
- ```
1008
-
1009
- **Frontend HTML example:**
1010
- ```html
1011
- <form method="post" action="/api/users/login">
1012
- <label>Email</label>
1013
- <input type="email" name="email" required autofocus>
1014
- <label>Password</label>
1015
- <input type="password" name="password" required>
1016
- <button type="submit">Login</button>
1017
- </form>
1018
- ```
1019
-
1020
- ### Logout Example
1021
-
1022
- To log out a user, call the `services.Authentication.logout()` method. This removes the `req.user` property and clears the login session:
1023
-
1024
- ```js
1025
- import {Router} from 'express';
1026
- import * as expx from 'express-sweet';
229
+ router.post('/api/login', async (req, res, next) => {
230
+ const ok = await expx.Authentication.authenticate(req, res, next);
231
+ res.json({ success: ok });
232
+ });
1027
233
 
1028
- const router = Router();
1029
234
  router.get('/logout', (req, res) => {
1030
- expx.services.Authentication.logout(req);
1031
- res.redirect('/login');
235
+ expx.Authentication.logout(req);
236
+ res.redirect('/');
1032
237
  });
1033
238
 
1034
239
  export default router;
1035
240
  ```
1036
241
 
1037
- **Frontend HTML example:**
1038
- ```html
1039
- <a href="/api/users/logout">Logout</a>
1040
- ```
1041
-
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).
1043
-
1044
- </details>
242
+ Full reference (Redis sessions, redirect helpers, route protection flow) → [docs/authentication.md](docs/authentication.md)
1045
243
 
1046
- <details>
1047
- <summary><strong>Examples</strong></summary>
244
+ ## Routing
1048
245
 
1049
- ## Examples
246
+ Express Sweet uses **file-based routing**. Files in the `routes/` directory are automatically mapped to URL endpoints:
1050
247
 
1051
- ### RESTful API Development
248
+ ```
249
+ routes/
250
+ home.js → /home
251
+ about.js → /about
252
+ api/
253
+ users.js → /api/users
254
+ posts.js → /api/posts
255
+ ```
1052
256
 
1053
- Build RESTful APIs with essential CRUD operations:
257
+ Each route file exports an Express `Router`:
1054
258
 
1055
259
  ```js
1056
- import {Router} from 'express';
1057
- import BookModel from '../models/BookModel.js';
1058
-
260
+ // routes/api/users.js
261
+ import { Router } from 'express';
1059
262
  const router = Router();
1060
263
 
1061
- // GET /api/books - List all books
1062
- router.get('/books', async (req, res, next) => {
1063
- try {
1064
- const books = await BookModel.findAll({
1065
- order: [['created', 'DESC']],
1066
- include: ['UserModel']
1067
- });
1068
-
1069
- res.json({ books });
1070
- } catch (error) {
1071
- next(error);
1072
- }
1073
- });
1074
-
1075
- // POST /api/books - Create a new book
1076
- router.post('/books', async (req, res, next) => {
1077
- try {
1078
- const { title, userId } = req.body;
1079
-
1080
- const newBook = await BookModel.create({
1081
- title,
1082
- userId: userId || req.user.id
1083
- });
1084
-
1085
- res.status(201).json({
1086
- success: true,
1087
- book: newBook
1088
- });
1089
- } catch (error) {
1090
- next(error);
1091
- }
1092
- });
1093
-
1094
- // PUT /api/books/:id - Update a book
1095
- router.put('/books/:id', async (req, res, next) => {
1096
- try {
1097
- const { title } = req.body;
1098
- const bookId = req.params.id;
1099
-
1100
- const [updatedRows] = await BookModel.update(
1101
- { title },
1102
- { where: { id: bookId } }
1103
- );
1104
-
1105
- if (updatedRows === 0) {
1106
- return res.status(404).json({
1107
- success: false,
1108
- message: 'Book not found'
1109
- });
1110
- }
1111
-
1112
- const updatedBook = await BookModel.findByPk(bookId);
1113
- res.json({
1114
- success: true,
1115
- book: updatedBook
1116
- });
1117
- } catch (error) {
1118
- next(error);
1119
- }
1120
- });
264
+ router.get('/', (req, res) => res.json([]));
265
+ router.get('/:id', (req, res) => res.json({ id: req.params.id }));
266
+ router.post('/', (req, res) => res.json({ created: true }));
1121
267
 
1122
268
  export default router;
1123
269
  ```
1124
270
 
1125
- ### Advanced View Usage
271
+ Set `default_router: '/home'` in `config.js` to also mount that route on `/`.
1126
272
 
1127
- Comprehensive view rendering with layouts and data:
273
+ Full reference → [docs/routing.md](docs/routing.md)
1128
274
 
1129
- ```js
1130
- import {Router} from 'express';
1131
- import UserModel from '../models/UserModel.js';
1132
- import BookModel from '../models/BookModel.js';
275
+ ## View Engine
1133
276
 
1134
- const router = Router();
277
+ Handlebars is pre-configured as the template engine. Express Sweet ships with 37 built-in helpers across 9 categories:
1135
278
 
1136
- // Render page with custom layout
1137
- router.get('/profile/:id', async (req, res) => {
1138
- try {
1139
- const user = await UserModel.findOne({
1140
- where: { id: req.params.id },
1141
- include: ['ProfileModel']
1142
- });
1143
-
1144
- if (!user) {
1145
- return res.status(404).render('errors/404', {
1146
- title: 'User Not Found'
1147
- });
1148
- }
279
+ | Category | Helpers |
280
+ |----------|---------|
281
+ | **Comparison** | `eq`, `eqw`, `neq`, `neqw`, `lt`, `lte`, `gt`, `gte`, `not`, `ifx` |
282
+ | **Comparison** (cont.) | `empty`, `notEmpty`, `count`, `and`, `or`, `coalesce`, `includes`, `regexMatch` |
283
+ | **Math** | `add`, `sub`, `multiply`, `divide`, `ceil`, `floor`, `abs` |
284
+ | **String** | `replace`, `split`, `formatBytes` |
285
+ | **Date** | `formatDate` |
286
+ | **Number** | `number2locale` |
287
+ | **HTML** | `cacheBusting`, `stripTags` |
288
+ | **Array** | `findObjectInArray` |
289
+ | **Object** | `jsonStringify`, `jsonParse` |
290
+ | **Layout** | `block`, `contentFor` |
1149
291
 
1150
- const userBooks = await BookModel.findAll({
1151
- where: { userId: req.params.id },
1152
- order: [['created', 'DESC']],
1153
- limit: 10
1154
- });
1155
-
1156
- res.render('profile', {
1157
- title: `${user.name}'s Profile`,
1158
- user,
1159
- books: userBooks,
1160
- layout: 'layout/profile'
1161
- });
1162
- } catch (error) {
1163
- next(error);
1164
- }
1165
- });
1166
-
1167
- // Render partial view without layout
1168
- router.get('/api/partial/user-stats', async (req, res) => {
1169
- try {
1170
- const bookCount = await BookModel.count({
1171
- where: { userId: req.user.id }
1172
- });
1173
-
1174
- res.render('partials/user-stats', {
1175
- bookCount,
1176
- layout: null
1177
- });
1178
- } catch (error) {
1179
- next(error);
1180
- }
1181
- });
292
+ ```handlebars
293
+ {{#if (eq role 'admin')}}
294
+ <span class="badge">Admin</span>
295
+ {{/if}}
1182
296
 
1183
- export default router;
297
+ {{formatDate 'YYYY/MM/DD' createdAt}}
298
+ {{number2locale price 'en-US'}}
299
+ {{add subtotal tax}}
1184
300
  ```
1185
301
 
1186
- ### Environment-Specific Configuration
302
+ Full helper reference → [docs/view-engine.md](docs/view-engine.md)
1187
303
 
1188
- Configure different settings for development, testing, and production:
304
+ ## File Upload
1189
305
 
1190
- ```js
1191
- // config/config.js
1192
- const isDevelopment = process.env.NODE_ENV === 'development';
1193
- const isProduction = process.env.NODE_ENV === 'production';
306
+ Multer-based file upload with per-route middleware resolution.
1194
307
 
308
+ ```js
309
+ // config/upload.js
1195
310
  export default {
1196
- env_path: '.env',
1197
- cors_enabled: isDevelopment,
1198
- max_body_size: isProduction ? '10mb' : '100mb',
1199
-
1200
- // Custom error handling
1201
- hook_handle_error: (error, req, res, next) => {
1202
- if (error.status === 404) {
1203
- res.status(404).render('errors/404', {
1204
- title: 'Page Not Found'
1205
- });
1206
- } else {
1207
- if (isProduction) {
1208
- console.error('Server Error:', error);
1209
- }
1210
-
1211
- res.status(500).render('errors/500', {
1212
- title: 'Server Error',
1213
- error: isDevelopment ? error : null
1214
- });
311
+ enabled: true,
312
+ resolve_middleware: (req, multer) => {
313
+ if (req.path === '/api/avatar' && req.method === 'POST') {
314
+ return multer({ storage: multer.memoryStorage() }).single('avatar');
1215
315
  }
316
+ return null;
1216
317
  },
1217
-
1218
- // Custom Ajax detection
1219
- is_ajax: (req) => {
1220
- return req.xhr ||
1221
- req.path.startsWith('/api/') ||
1222
- req.get('Accept')?.includes('application/json');
1223
- }
1224
318
  };
1225
319
  ```
1226
320
 
1227
- ### Error Handling
1228
-
1229
- Implement proper error handling in your routes:
1230
-
1231
- ```js
1232
- import {Router} from 'express';
1233
- import UserModel from '../models/UserModel.js';
321
+ Full reference (disk storage, multiple files, file filtering) → [docs/file-upload.md](docs/file-upload.md)
1234
322
 
1235
- const router = Router();
323
+ ## Demo
1236
324
 
1237
- // Route with comprehensive error handling
1238
- router.post('/users', async (req, res, next) => {
1239
- try {
1240
- const { name, email, password } = req.body;
1241
-
1242
- // Input validation
1243
- if (!email || !email.includes('@')) {
1244
- return res.status(400).json({
1245
- success: false,
1246
- message: 'Invalid email format'
1247
- });
1248
- }
1249
-
1250
- if (!password || password.length < 6) {
1251
- return res.status(400).json({
1252
- success: false,
1253
- message: 'Password must be at least 6 characters'
1254
- });
1255
- }
1256
-
1257
- // Check if user already exists
1258
- const existingUser = await UserModel.findOne({
1259
- where: { email }
1260
- });
1261
-
1262
- if (existingUser) {
1263
- return res.status(409).json({
1264
- success: false,
1265
- message: 'User already exists with this email'
1266
- });
1267
- }
1268
-
1269
- // Create user
1270
- const user = await UserModel.create({
1271
- name,
1272
- email,
1273
- password
1274
- });
1275
-
1276
- res.status(201).json({
1277
- success: true,
1278
- user: {
1279
- id: user.id,
1280
- name: user.name,
1281
- email: user.email
1282
- }
1283
- });
1284
-
1285
- } catch (error) {
1286
- next(error);
1287
- }
1288
- });
325
+ A full-featured demo app is included in [demo/](demo/) — auth, CRUD, file uploads, error pages, all wired up. Both ESM and CommonJS versions. It runs against the build in this repository: `docker compose run --rm build`, then `cd demo/esm && docker compose up`. See [demo/README.md](demo/README.md) for what it covers and [CONTRIBUTING.md](CONTRIBUTING.md) for the development setup.
1289
326
 
1290
- export default router;
1291
- ```
327
+ ## Migration from v4
1292
328
 
1293
- </details>
329
+ Upgrading from v4? See the migration guide → [docs/migration-v5.md](docs/migration-v5.md)
1294
330
 
1295
- ## Release Notes
331
+ ## Changelog
1296
332
 
1297
- All changes and version history can be found in the [CHANGELOG.md](CHANGELOG.md).
333
+ See [CHANGELOG.md](CHANGELOG.md) for the full release history.
1298
334
 
1299
335
  ## Author
1300
336
 
1301
- **Takuya Motoshima**
337
+ **shumatsumonobu**
1302
338
 
1303
- * [github/takuya-motoshima](https://github.com/takuya-motoshima)
1304
- * [x/takuya_motech](https://x.com/takuya_motech)
339
+ * [github/shumatsumonobu](https://github.com/shumatsumonobu)
340
+ * [x/shumatsumonobu](https://x.com/shumatsumonobu)
1305
341
  * [facebook/takuya.motoshima.7](https://www.facebook.com/takuya.motoshima.7)
1306
342
 
1307
343
  ## License
1308
344
 
1309
- [MIT](LICENSE)
345
+ [MIT](LICENSE)