express-sweet 3.0.2 → 5.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.
- package/CHANGELOG.md +224 -418
- package/LICENSE +1 -1
- package/README.md +211 -1026
- package/dist/build.cjs +37 -72
- package/dist/build.mjs +37 -72
- package/package.json +50 -64
- package/screenshots/avatar.png +0 -0
- package/screenshots/edit-profile.png +0 -0
- package/screenshots/hero-banner.png +0 -0
- package/screenshots/home.png +0 -0
- package/screenshots/mount-flow.mmd +11 -0
- package/screenshots/mount-flow.png +0 -0
- package/screenshots/new-person.png +0 -0
- package/screenshots/people.png +0 -0
- package/screenshots/sign-in.png +0 -0
- package/types/database/DatabaseManager.d.ts +15 -10
- package/types/database/Model.d.ts +29 -43
- package/types/database/index.d.ts +0 -1
- package/types/database/loadModels.d.ts +7 -13
- package/types/helpers/array.d.ts +21 -0
- package/types/helpers/comparison.d.ts +217 -0
- package/types/helpers/date.d.ts +20 -0
- package/types/helpers/html.d.ts +35 -0
- package/types/{handlebars_helpers → helpers}/index.d.ts +0 -2
- package/types/helpers/layouts.d.ts +29 -0
- package/types/helpers/math.d.ts +85 -0
- package/types/helpers/number.d.ts +19 -0
- package/types/helpers/object.d.ts +28 -0
- package/types/helpers/string.d.ts +45 -0
- package/types/index.d.ts +7 -52
- package/types/middleware/auth.d.ts +186 -0
- package/types/middleware/cors.d.ts +19 -0
- package/types/middleware/env.d.ts +24 -0
- package/types/middleware/error.d.ts +26 -0
- package/types/middleware/globals.d.ts +13 -0
- package/types/{middlewares → middleware}/index.d.ts +19 -12
- package/types/middleware/locals.d.ts +33 -0
- package/types/middleware/parser.d.ts +30 -0
- package/types/middleware/router.d.ts +31 -0
- package/types/middleware/views.d.ts +37 -0
- package/types/mount.d.ts +34 -3
- package/types/{interfaces/BasicConfig.d.ts → types/AppConfig.d.ts} +18 -25
- package/types/{interfaces → types}/AuthenticationConfig.d.ts +10 -11
- package/types/{interfaces → types}/DatabaseConfig.d.ts +1 -1
- package/types/{interfaces → types}/LoggingConfig.d.ts +0 -1
- package/types/types/UploadConfig.d.ts +72 -0
- package/types/{interfaces → types}/ViewConfig.d.ts +1 -2
- package/types/{interfaces → types}/index.d.ts +7 -4
- package/types/utils/index.d.ts +7 -4
- package/types/utils/loadAppConfig.d.ts +17 -0
- package/types/utils/loadAuthenticationConfig.d.ts +1 -1
- package/types/utils/loadLoggingConfig.d.ts +1 -1
- package/types/utils/loadUploadConfig.d.ts +20 -0
- package/types/utils/loadViewConfig.d.ts +1 -1
- package/configuration_sample/cjs/authentication.js +0 -138
- package/configuration_sample/cjs/config.js +0 -91
- package/configuration_sample/cjs/database.js +0 -121
- package/configuration_sample/cjs/logging.js +0 -41
- package/configuration_sample/cjs/view.js +0 -54
- package/configuration_sample/esm/authentication.js +0 -136
- package/configuration_sample/esm/config.js +0 -91
- package/configuration_sample/esm/database.js +0 -121
- package/configuration_sample/esm/logging.js +0 -41
- package/configuration_sample/esm/view.js +0 -54
- package/screencaps/belongs-to-many.png +0 -0
- package/screencaps/belongs-to.png +0 -0
- package/screencaps/demonstration.webp +0 -0
- package/screencaps/has-many.png +0 -0
- package/screencaps/has-one.png +0 -0
- package/types/handlebars_helpers/array.d.ts +0 -22
- package/types/handlebars_helpers/comparison.d.ts +0 -222
- package/types/handlebars_helpers/date.d.ts +0 -19
- package/types/handlebars_helpers/html.d.ts +0 -31
- package/types/handlebars_helpers/layouts.d.ts +0 -25
- package/types/handlebars_helpers/math.d.ts +0 -74
- package/types/handlebars_helpers/number.d.ts +0 -18
- package/types/handlebars_helpers/object.d.ts +0 -21
- package/types/handlebars_helpers/string.d.ts +0 -45
- package/types/middlewares/Authentication.d.ts +0 -52
- package/types/middlewares/CORS.d.ts +0 -30
- package/types/middlewares/Environment.d.ts +0 -36
- package/types/middlewares/ErrorHandler.d.ts +0 -34
- package/types/middlewares/Global.d.ts +0 -27
- package/types/middlewares/Http.d.ts +0 -29
- package/types/middlewares/Local.d.ts +0 -42
- package/types/middlewares/View.d.ts +0 -49
- package/types/routing/Router.d.ts +0 -56
- package/types/routing/index.d.ts +0 -37
- package/types/services/Authentication.d.ts +0 -95
- package/types/services/index.d.ts +0 -33
- package/types/types/global.d.ts +0 -38
- package/types/utils/Types.d.ts +0 -23
- package/types/utils/loadBasicConfig.d.ts +0 -17
package/README.md
CHANGED
|
@@ -1,1160 +1,345 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
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)
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="screenshots/hero-banner.png" alt="Express Sweet" width="100%">
|
|
3
|
+
</p>
|
|
57
4
|
|
|
58
|
-
|
|
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>
|
|
59
10
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
- **Automatic Routing**: Files in the `routes/` directory are automatically mapped to URL endpoints
|
|
63
|
-
- **Database ORM**: Built-in Sequelize integration with automatic connection management
|
|
64
|
-
- **Authentication**: Passport-based authentication system with session management
|
|
65
|
-
- **Template Engine**: Handlebars view engine with custom helpers and layout support
|
|
66
|
-
- **Environment Management**: Automatic environment variable loading and configuration
|
|
67
|
-
- **Logging**: Morgan-based HTTP request logging with customizable formats
|
|
68
|
-
- **CORS Support**: Built-in Cross-Origin Resource Sharing support
|
|
69
|
-
- **Project Generator**: Command-line tool to quickly scaffold new applications
|
|
70
|
-
|
|
71
|
-
## API Reference
|
|
72
|
-
|
|
73
|
-
📖 **[Complete API Documentation](https://takuya-motoshima.github.io/express-sweet/)**
|
|
74
|
-
|
|
75
|
-
The comprehensive API reference includes detailed documentation for:
|
|
76
|
-
|
|
77
|
-
- **[Database](https://takuya-motoshima.github.io/express-sweet/modules/database.html)**: `DatabaseManager`, `Model` classes with full Sequelize integration, and `loadModels` utility
|
|
78
|
-
- **[Services](https://takuya-motoshima.github.io/express-sweet/modules/services.html)**: `Authentication` service for user login, logout, and session management
|
|
79
|
-
- **[Handlebars Helpers](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.html)**: Complete collection of template helpers including:
|
|
80
|
-
- **[Array](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.array.html)**: `findObjectInArray`
|
|
81
|
-
- **[Comparison](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.comparison.html)**: `eq`, `gt`, `lt`, `and`, `or`, `empty`, `includes`, etc.
|
|
82
|
-
- **[String](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.string.html)**: `replace`, `split`, `formatBytes`
|
|
83
|
-
- **[Date](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.date.html)**: `formatDate`
|
|
84
|
-
- **[Math](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.math.html)**: `add`, `subtract`, `multiply`, `divide`, `ceil`, `floor`, `abs`
|
|
85
|
-
- **[Number](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.number.html)**: `number2locale`
|
|
86
|
-
- **[Object](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.object.html)**: `jsonStringify`, `jsonParse`
|
|
87
|
-
- **[HTML](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.html.html)**: `cacheBusting`, `stripTags`
|
|
88
|
-
- **[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
|
|
92
|
-
- **[Utilities](https://takuya-motoshima.github.io/express-sweet/modules/utils.html)**: Type checking functions and configuration loaders
|
|
93
|
-
- **[Mount Function](https://takuya-motoshima.github.io/express-sweet/variables/mount.html)**: Application initialization and setup
|
|
94
|
-
|
|
95
|
-
## EXPRESS SWEET Generator
|
|
96
|
-
|
|
97
|
-
Use the application generator tool, `express-sweet-generator`, to quickly create an application skeleton.
|
|
98
|
-
|
|
99
|
-

|
|
100
|
-
|
|
101
|
-
1. **Install the generator globally** as an npm package:
|
|
102
|
-
```bash
|
|
103
|
-
npm install -g express-sweet-generator
|
|
104
|
-
```
|
|
105
|
-
|
|
106
|
-
2. **Display command options** with the `-h` flag:
|
|
107
|
-
```bash
|
|
108
|
-
express-sweet -h
|
|
109
|
-
|
|
110
|
-
Usage: express-sweet [options] [dir]
|
|
111
|
-
|
|
112
|
-
Options:
|
|
113
|
-
--version output the version number
|
|
114
|
-
-o, --output <output> add output <module> support (esm|cjs) (defaults to cjs)
|
|
115
|
-
-p, --port <port> application listening port (default: 3000)
|
|
116
|
-
-f, --force force on non-empty directory
|
|
117
|
-
-h, --help output usage information
|
|
118
|
-
```
|
|
119
|
-
|
|
120
|
-
3. **Create your application**. For example, the following creates an Express app named `myapp` using ESM modules:
|
|
121
|
-
```bash
|
|
122
|
-
express-sweet -o esm myapp
|
|
123
|
-
```
|
|
124
|
-
|
|
125
|
-
4. **Install dependencies** and start developing:
|
|
126
|
-
```bash
|
|
127
|
-
cd myapp/
|
|
128
|
-
npm install
|
|
129
|
-
```
|
|
11
|
+
One function call. Full stack. Auth, ORM, routing, views — everything snaps together so you can ship fast and stay sharp.
|
|
130
12
|
|
|
131
|
-
##
|
|
13
|
+
## What is Express Sweet?
|
|
14
|
+
|
|
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.
|
|
16
|
+
|
|
17
|
+
```js
|
|
18
|
+
import express from 'express';
|
|
19
|
+
import * as expx from 'express-sweet';
|
|
132
20
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
```sql
|
|
138
|
-
-- Create database
|
|
139
|
-
CREATE DATABASE IF NOT EXISTS `sample_db` DEFAULT CHARACTER SET utf8mb4;
|
|
140
|
-
|
|
141
|
-
USE `sample_db`;
|
|
142
|
-
|
|
143
|
-
-- User table: Stores user account information
|
|
144
|
-
CREATE TABLE `user` (
|
|
145
|
-
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
|
|
146
|
-
`name` varchar(30) NOT NULL COMMENT 'User display name',
|
|
147
|
-
`email` varchar(255) NOT NULL COMMENT 'User email address (unique)',
|
|
148
|
-
`password` varchar(100) NOT NULL COMMENT 'Encrypted password',
|
|
149
|
-
`icon` varchar(768) NOT NULL DEFAULT MD5(RAND()) COMMENT 'User icon path or identifier',
|
|
150
|
-
`created` datetime NOT NULL DEFAULT current_timestamp() COMMENT 'Record creation timestamp',
|
|
151
|
-
`modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT 'Record last modified timestamp',
|
|
152
|
-
PRIMARY KEY (`id`),
|
|
153
|
-
UNIQUE KEY `ukUserEmail` (`email`),
|
|
154
|
-
UNIQUE KEY `ukUserIcon`(`icon`)
|
|
155
|
-
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='User accounts table';
|
|
156
|
-
|
|
157
|
-
-- Profile table: Stores additional user profile information
|
|
158
|
-
CREATE TABLE `profile` (
|
|
159
|
-
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
|
|
160
|
-
`userId` int(10) unsigned NOT NULL COMMENT 'Foreign key to user table',
|
|
161
|
-
`address` varchar(255) NOT NULL COMMENT 'User address',
|
|
162
|
-
`tel` varchar(14) NOT NULL COMMENT 'User telephone number',
|
|
163
|
-
`created` datetime NOT NULL DEFAULT current_timestamp() COMMENT 'Record creation timestamp',
|
|
164
|
-
`modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT 'Record last modified timestamp',
|
|
165
|
-
PRIMARY KEY (`id`),
|
|
166
|
-
UNIQUE KEY `ukProfileUserId` (`userId`),
|
|
167
|
-
CONSTRAINT `fkProfileUser` FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE CASCADE
|
|
168
|
-
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='User profiles table';
|
|
169
|
-
|
|
170
|
-
-- Comment table: Stores user comments
|
|
171
|
-
CREATE TABLE `comment` (
|
|
172
|
-
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
|
|
173
|
-
`userId` int(10) unsigned NOT NULL COMMENT 'Foreign key to user table',
|
|
174
|
-
`text` text NOT NULL COMMENT 'Comment text content',
|
|
175
|
-
`created` datetime NOT NULL DEFAULT current_timestamp() COMMENT 'Record creation timestamp',
|
|
176
|
-
`modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT 'Record last modified timestamp',
|
|
177
|
-
PRIMARY KEY (`id`),
|
|
178
|
-
CONSTRAINT `fkCommentUser` FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE CASCADE
|
|
179
|
-
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='User comments table';
|
|
180
|
-
|
|
181
|
-
-- Book table: Stores user books
|
|
182
|
-
CREATE TABLE `book` (
|
|
183
|
-
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Primary key',
|
|
184
|
-
`userId` int(10) unsigned NOT NULL COMMENT 'Foreign key to user table',
|
|
185
|
-
`title` text NOT NULL COMMENT 'Book title',
|
|
186
|
-
`created` datetime NOT NULL DEFAULT current_timestamp() COMMENT 'Record creation timestamp',
|
|
187
|
-
`modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT 'Record last modified timestamp',
|
|
188
|
-
PRIMARY KEY (`id`),
|
|
189
|
-
UNIQUE KEY `ukBookTitle` (`userId`, `title`(255)),
|
|
190
|
-
CONSTRAINT `fkBookUser` FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE CASCADE
|
|
191
|
-
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='User books table';
|
|
192
|
-
|
|
193
|
-
-- Sample data insertion
|
|
194
|
-
INSERT INTO `user` (`id`, `email`, `password`, `name`, `icon`) VALUES
|
|
195
|
-
(1, 'robin@example.com', 'password', 'Robin', '/upload/1.png'),
|
|
196
|
-
(2, 'taylor@example.com', 'password', 'Taylor', '/upload/2.png');
|
|
197
|
-
|
|
198
|
-
INSERT INTO `profile` (`userId`, `address`, `tel`) VALUES
|
|
199
|
-
(1, '777 Brockton Avenue, Abington MA 2351', '202-555-0105'),
|
|
200
|
-
(2, '30 Memorial Drive, Avon MA 2322', '');
|
|
201
|
-
|
|
202
|
-
INSERT INTO `comment` (`userId`, `text`) VALUES
|
|
203
|
-
(1, 'From Robin #1'),
|
|
204
|
-
(1, 'From Robin #2'),
|
|
205
|
-
(2, 'From Taylor #1');
|
|
206
|
-
|
|
207
|
-
INSERT INTO `book` (`userId`, `title`) VALUES
|
|
208
|
-
(1, 'Beautiful'),
|
|
209
|
-
(1, 'Lose Yourself'),
|
|
210
|
-
(2, 'When Im Gone');
|
|
21
|
+
const app = express();
|
|
22
|
+
await expx.mount(app);
|
|
23
|
+
app.listen(3000);
|
|
211
24
|
```
|
|
212
25
|
|
|
213
|
-
|
|
26
|
+
That's it. Four lines of real code and you have a fully configured web application.
|
|
214
27
|
|
|
215
|
-
|
|
28
|
+
## Features
|
|
216
29
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
test: {
|
|
227
|
-
username: 'root',
|
|
228
|
-
password: 'password',
|
|
229
|
-
database: 'sample_db',
|
|
230
|
-
host: 'localhost',
|
|
231
|
-
dialect: 'mariadb'
|
|
232
|
-
},
|
|
233
|
-
production: {
|
|
234
|
-
username: 'root',
|
|
235
|
-
password: 'password',
|
|
236
|
-
database: 'sample_db',
|
|
237
|
-
host: 'localhost',
|
|
238
|
-
dialect: 'mariadb'
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
```
|
|
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
|
|
38
|
+
- **Dual format** — Ships as both ESM and CommonJS
|
|
242
39
|
|
|
243
|
-
|
|
40
|
+
## Screenshots
|
|
244
41
|
|
|
245
|
-
|
|
42
|
+
| Sign In | Home | People |
|
|
43
|
+
|---------|------|--------|
|
|
44
|
+
|  |  |  |
|
|
246
45
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
46
|
+
| New Person | Edit Profile | Change Avatar |
|
|
47
|
+
|------------|-------------|---------------|
|
|
48
|
+
|  |  |  |
|
|
250
49
|
|
|
251
|
-
|
|
50
|
+
## Quick Start
|
|
252
51
|
|
|
253
|
-
|
|
52
|
+
### The fast way — use the generator
|
|
254
53
|
|
|
255
54
|
```bash
|
|
55
|
+
npx express-sweet myapp
|
|
56
|
+
cd myapp
|
|
57
|
+
npm install
|
|
58
|
+
npm run setup
|
|
256
59
|
npm start
|
|
257
60
|
```
|
|
258
61
|
|
|
259
|
-
|
|
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.
|
|
260
63
|
|
|
261
|
-
|
|
64
|
+
### From scratch
|
|
262
65
|
|
|
263
|
-
|
|
66
|
+
#### Install
|
|
264
67
|
|
|
265
68
|
```bash
|
|
266
|
-
|
|
267
|
-
├── .env # Environment variables configuration
|
|
268
|
-
├── app.js # Main application entry point
|
|
269
|
-
├── ecosystem.config.js # PM2 process manager configuration
|
|
270
|
-
├── nginx.sample.conf # Sample Nginx reverse proxy configuration
|
|
271
|
-
├── package.json # Node.js dependencies and scripts
|
|
272
|
-
├── bin
|
|
273
|
-
│ └── www # Application startup script
|
|
274
|
-
├── client # Frontend application directory
|
|
275
|
-
│ ├── package.json # Frontend dependencies
|
|
276
|
-
│ ├── webpack.config.js # Webpack bundler configuration
|
|
277
|
-
│ └── src # Frontend source code
|
|
278
|
-
├── config # Application configuration files
|
|
279
|
-
│ ├── authentication.js # Authentication and session settings
|
|
280
|
-
│ ├── config.js # Core application configuration
|
|
281
|
-
│ ├── database.js # Database connection settings
|
|
282
|
-
│ ├── logging.js # HTTP request logging configuration
|
|
283
|
-
│ └── view.js # Template engine configuration
|
|
284
|
-
├── errors # Custom error classes
|
|
285
|
-
│ └── UserNotFound.js # Custom error definitions
|
|
286
|
-
├── models # Database models (Sequelize ORM)
|
|
287
|
-
│ ├── BookModel.js # Book entity model
|
|
288
|
-
│ ├── CommentModel.js # Comment entity model
|
|
289
|
-
│ ├── ProfileModel.js # User profile model
|
|
290
|
-
│ └── UserModel.js # User entity model
|
|
291
|
-
├── public # Static assets directory
|
|
292
|
-
│ ├── build # Compiled frontend assets
|
|
293
|
-
│ └── upload # User uploaded files
|
|
294
|
-
├── routes # Express route definitions
|
|
295
|
-
│ ├── login.js # Authentication routes
|
|
296
|
-
│ ├── users.js # User management routes
|
|
297
|
-
│ └── api # API endpoints
|
|
298
|
-
│ └── users.js # User API routes
|
|
299
|
-
├── shared # Shared utilities and helpers
|
|
300
|
-
│ ├── CustomValidation.js # Custom validation functions
|
|
301
|
-
│ └── empty.js # Utility functions
|
|
302
|
-
└── views # Handlebars template files
|
|
303
|
-
├── edit-personal.hbs # Profile editing template
|
|
304
|
-
├── error.hbs # Error page template
|
|
305
|
-
├── login.hbs # Login page template
|
|
306
|
-
├── personal.hbs # Profile display template
|
|
307
|
-
├── users.hbs # Users listing template
|
|
308
|
-
├── layout # Layout templates
|
|
309
|
-
│ └── default.hbs # Default page layout
|
|
310
|
-
└── partials # Reusable template components
|
|
311
|
-
└── .gitkeep # Placeholder for partial templates
|
|
69
|
+
npm install express-sweet
|
|
312
70
|
```
|
|
313
71
|
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
**Configuration (`config/`)**
|
|
317
|
-
Contains all application settings divided by functionality. Modify these files to customize database connections, authentication behavior, view rendering, and logging.
|
|
318
|
-
|
|
319
|
-
**Models (`models/`)**
|
|
320
|
-
Database entities using Sequelize ORM. Each model represents a database table and defines the schema, relationships, and business logic for that entity.
|
|
321
|
-
|
|
322
|
-
**Routes (`routes/`)**
|
|
323
|
-
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`.
|
|
324
|
-
|
|
325
|
-
**Views (`views/`)**
|
|
326
|
-
Handlebars templates for rendering HTML pages. The `layout/` directory contains base templates, while `partials/` holds reusable components.
|
|
327
|
-
|
|
328
|
-
**Public (`public/`)**
|
|
329
|
-
Static files served directly by the web server. The `build/` directory contains compiled frontend assets, while `upload/` stores user-generated content.
|
|
330
|
-
|
|
331
|
-
## Configuration
|
|
72
|
+
#### Create config files
|
|
332
73
|
|
|
333
|
-
|
|
74
|
+
Express Sweet uses convention-based configuration. Create a `config/` directory with the files you need:
|
|
334
75
|
|
|
335
|
-
### Environment Variables
|
|
336
|
-
|
|
337
|
-
If you set the environment variable file in `env_path` of `config/config.js`, the values will be automatically loaded into `process.env`.
|
|
338
|
-
|
|
339
|
-
The `NODE_ENV` environment variable is required. If omitted, `development` is used by default.
|
|
340
|
-
|
|
341
|
-
You can access environment variables and perform custom logic as needed:
|
|
342
|
-
```js
|
|
343
|
-
if (process.env.NODE_ENV === 'development') {
|
|
344
|
-
// Development-specific logic
|
|
345
|
-
}
|
|
346
76
|
```
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
Set to `true` to allow requests from other domains.
|
|
365
|
-
|
|
366
|
-
- **`max_body_size: string|number`**
|
|
367
|
-
Maximum request body size. Defaults to `100kb`.
|
|
368
|
-
If a number, specifies bytes. If a string, parsed by the [bytes library](https://www.npmjs.com/package/bytes).
|
|
369
|
-
|
|
370
|
-
- **`router_dir: string`**
|
|
371
|
-
Absolute path to the router directory. Defaults to `<application root>/routes`.
|
|
372
|
-
|
|
373
|
-
- **`default_router: string`**
|
|
374
|
-
Endpoint to run when the root URL is requested. Defaults to `undefined`.
|
|
375
|
-
EXPRESS SWEET can load a default router when no URI is present (root URL `/` requests).
|
|
376
|
-
|
|
377
|
-
- **`rewrite_base_url: (baseUrl: string) => string`**
|
|
378
|
-
Hook to rewrite the base URL for `app.locals.baseUrl` and view's `baseUrl` variable.
|
|
379
|
-
Default value is the referrer's origin (e.g., `https://example.com`).
|
|
380
|
-
|
|
381
|
-
- **`is_ajax: (req: express.Request) => boolean`**
|
|
382
|
-
Custom logic to determine Ajax requests.
|
|
383
|
-
Defaults to checking for XMLHttpRequest in headers (`req.xhr`).
|
|
384
|
-
|
|
385
|
-
- **`hook_handle_error: (error: any, req: express.Request, res: express.Response, next: express.NextFunction) => void`**
|
|
386
|
-
Custom error handling hook. If unset, returns appropriate HTTP status codes.
|
|
387
|
-
|
|
388
|
-
### Database Configuration (`config/database.js`)
|
|
389
|
-
|
|
390
|
-
Database settings are defined in the `config/database.js` file.
|
|
391
|
-
|
|
392
|
-
**Sample configurations:**
|
|
393
|
-
- [ESM Configuration](configuration_sample/esm/database.js)
|
|
394
|
-
- [CJS Configuration](configuration_sample/cjs/database.js)
|
|
395
|
-
|
|
396
|
-
**Configuration Options:**
|
|
397
|
-
|
|
398
|
-
- **`username: string`** - Database authentication username
|
|
399
|
-
- **`password: string|null`** - Database authentication password (default: `null`)
|
|
400
|
-
- **`database: string`** - Database name
|
|
401
|
-
- **`host: string`** - Database host
|
|
402
|
-
- **`port: number|null`** - Database port (default: auto-select)
|
|
403
|
-
- **`dialect: string`** - Database dialect: `mariadb`, `mysql`, `postgres`, `sqlite`, or `mssql`
|
|
404
|
-
- **`logging: boolean|(...message: any[]) => void`** - Query logging (default: `false`)
|
|
405
|
-
- **`timezone: string`** - Database timezone (e.g., `'+09:00'` for JST)
|
|
406
|
-
|
|
407
|
-
### Authentication Configuration (`config/authentication.js`)
|
|
408
|
-
|
|
409
|
-
User authentication settings are defined in the `config/authentication.js` file.
|
|
410
|
-
|
|
411
|
-
**Sample configurations:**
|
|
412
|
-
- [ESM Configuration](configuration_sample/esm/authentication.js)
|
|
413
|
-
- [CJS Configuration](configuration_sample/cjs/authentication.js)
|
|
414
|
-
|
|
415
|
-
### View Configuration (`config/view.js`)
|
|
416
|
-
|
|
417
|
-
Template engine settings are defined in the `config/view.js` file.
|
|
418
|
-
|
|
419
|
-
**Sample configurations:**
|
|
420
|
-
- [ESM Configuration](configuration_sample/esm/view.js)
|
|
421
|
-
- [CJS Configuration](configuration_sample/cjs/view.js)
|
|
422
|
-
|
|
423
|
-
### Logging Configuration (`config/logging.js`)
|
|
424
|
-
|
|
425
|
-
HTTP request logging settings are defined in the `config/logging.js` file.
|
|
426
|
-
|
|
427
|
-
**Sample configurations:**
|
|
428
|
-
- [ESM Configuration](configuration_sample/esm/logging.js)
|
|
429
|
-
- [CJS Configuration](configuration_sample/cjs/logging.js)
|
|
430
|
-
|
|
431
|
-
## Routing
|
|
432
|
-
|
|
433
|
-
Routing determines how an application responds to client requests for specific endpoints, defined by a URI path and HTTP request method (GET, POST, etc.).
|
|
434
|
-
|
|
435
|
-
### Basic Routing
|
|
436
|
-
|
|
437
|
-
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.
|
|
438
|
-
|
|
439
|
-
**Example:** `routes/user.js` responds to `GET /user` requests:
|
|
440
|
-
```js
|
|
441
|
-
import {Router} from 'express';
|
|
442
|
-
|
|
443
|
-
const router = Router();
|
|
444
|
-
router.get('/', (req, res) => {
|
|
445
|
-
res.send('Hello World');
|
|
446
|
-
});
|
|
447
|
-
|
|
448
|
-
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
|
|
449
94
|
```
|
|
450
95
|
|
|
451
|
-
|
|
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.
|
|
452
97
|
|
|
453
|
-
|
|
98
|
+
#### Boot the app
|
|
454
99
|
|
|
455
|
-
**Example:** `routes/api/users.js` responds to `GET /api/users` requests:
|
|
456
100
|
```js
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
router.get('/', (req, res) => {
|
|
461
|
-
res.send('Hello World');
|
|
462
|
-
});
|
|
463
|
-
|
|
464
|
-
export default router;
|
|
465
|
-
```
|
|
466
|
-
|
|
467
|
-
### Default Routing
|
|
468
|
-
|
|
469
|
-
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';
|
|
470
104
|
|
|
471
|
-
|
|
472
|
-
|
|
105
|
+
const app = express();
|
|
106
|
+
await expx.mount(app);
|
|
107
|
+
app.listen(3000, () => console.log('Running on http://localhost:3000'));
|
|
473
108
|
```
|
|
474
109
|
|
|
475
|
-
Where `blog` corresponds to the router module name. Create the corresponding `routes/blog.js` module:
|
|
476
|
-
|
|
477
110
|
```js
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
const
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
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();
|
|
486
121
|
```
|
|
487
122
|
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
### Routing Methods
|
|
491
|
-
|
|
492
|
-
Express supports routing methods corresponding to HTTP methods:
|
|
493
|
-
|
|
494
|
-
- `checkout`, `copy`, `delete`, `get`, `head`, `lock`, `merge`, `mkactivity`, `mkcol`, `move`, `m-search`, `notify`, `options`, `patch`, `post`, `purge`, `put`, `report`, `search`, `subscribe`, `trace`, `unlock`, `unsubscribe`
|
|
495
|
-
|
|
496
|
-
For comprehensive routing documentation, see the [Express Routing Guide](https://expressjs.com/en/guide/routing.html#express-router).
|
|
497
|
-
|
|
498
|
-
## Model
|
|
499
|
-
|
|
500
|
-
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:
|
|
501
|
-
|
|
502
|
-
- **Automatic database connection management**
|
|
503
|
-
- **Built-in CRUD methods**
|
|
504
|
-
- **Query builder integration**
|
|
505
|
-
- **Model relationships and associations**
|
|
506
|
-
- **Data validation and hooks**
|
|
123
|
+
`mount()` initializes all middleware in a carefully ordered sequence:
|
|
507
124
|
|
|
508
|
-
|
|
125
|
+
<!-- Mermaid source: screenshots/mount-flow.mmd, regenerate with: npm run diagram -->
|
|
126
|
+

|
|
509
127
|
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
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.
|
|
128
|
+
## Configuration
|
|
513
129
|
|
|
514
|
-
|
|
515
|
-
```js
|
|
516
|
-
import BookModel from '../models/BookModel.js';
|
|
130
|
+
Six config files control the framework. All are optional — Express Sweet uses sensible defaults when a file is missing.
|
|
517
131
|
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
132
|
+
| File | Purpose | Key Options |
|
|
133
|
+
|------|---------|-------------|
|
|
134
|
+
| `config.js` | App basics | `cors_enabled`, `max_body_size`, `router_dir`, `default_router`, `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` |
|
|
524
140
|
|
|
525
|
-
|
|
526
|
-
// SQL: SELECT * FROM book
|
|
527
|
-
const allBooks = await BookModel.findAll();
|
|
141
|
+
Full option reference → [docs/configuration.md](docs/configuration.md)
|
|
528
142
|
|
|
529
|
-
|
|
530
|
-
// SQL: SELECT * FROM book WHERE userId = 1
|
|
531
|
-
const userBooks = await BookModel.findAll({
|
|
532
|
-
where: { userId: 1 }
|
|
533
|
-
});
|
|
143
|
+
## Database & Models
|
|
534
144
|
|
|
535
|
-
|
|
536
|
-
// SQL: UPDATE book SET title = 'Beautiful' WHERE id = 1
|
|
537
|
-
await BookModel.update(
|
|
538
|
-
{ title: 'Beautiful' },
|
|
539
|
-
{ where: { id: 1 } }
|
|
540
|
-
);
|
|
541
|
-
|
|
542
|
-
// Delete records
|
|
543
|
-
// SQL: DELETE FROM book WHERE id = 1
|
|
544
|
-
await BookModel.destroy({
|
|
545
|
-
where: { id: 1 }
|
|
546
|
-
});
|
|
145
|
+
Express Sweet wraps Sequelize with a `Model` base class and a `DatabaseManager` singleton.
|
|
547
146
|
|
|
548
|
-
|
|
549
|
-
// SQL: SELECT * FROM book WHERE title = 'Beautiful' LIMIT 1
|
|
550
|
-
const book = await BookModel.findOne({
|
|
551
|
-
where: { title: 'Beautiful' }
|
|
552
|
-
});
|
|
553
|
-
```
|
|
147
|
+
### Define a model
|
|
554
148
|
|
|
555
|
-
### Creating Custom Models
|
|
556
|
-
|
|
557
|
-
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.
|
|
558
|
-
|
|
559
|
-
**Basic model structure:**
|
|
560
149
|
```js
|
|
150
|
+
// models/UserModel.js
|
|
561
151
|
import * as expx from 'express-sweet';
|
|
562
152
|
|
|
563
|
-
export default class
|
|
153
|
+
export default class extends expx.database.Model {
|
|
564
154
|
static get table() {
|
|
565
155
|
return 'user';
|
|
566
156
|
}
|
|
567
157
|
|
|
568
158
|
static get attributes() {
|
|
569
159
|
return {
|
|
570
|
-
id:
|
|
571
|
-
|
|
572
|
-
primaryKey: true,
|
|
573
|
-
autoIncrement: true
|
|
574
|
-
},
|
|
575
|
-
name: this.DataTypes.STRING,
|
|
160
|
+
id: { type: this.DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
|
161
|
+
name: this.DataTypes.STRING,
|
|
576
162
|
email: this.DataTypes.STRING,
|
|
577
|
-
password: this.DataTypes.STRING,
|
|
578
|
-
created: this.DataTypes.DATE,
|
|
579
|
-
modified: this.DataTypes.DATE
|
|
580
163
|
};
|
|
581
164
|
}
|
|
582
165
|
}
|
|
583
166
|
```
|
|
584
167
|
|
|
585
|
-
###
|
|
586
|
-
|
|
587
|
-
EXPRESS SWEET supports Sequelize associations for building data relationships:
|
|
168
|
+
### CRUD
|
|
588
169
|
|
|
589
170
|
```js
|
|
590
|
-
|
|
591
|
-
static associate(models) {
|
|
592
|
-
// One-to-One: User has one Profile
|
|
593
|
-
this.hasOne(models.ProfileModel, {
|
|
594
|
-
foreignKey: 'userId'
|
|
595
|
-
});
|
|
596
|
-
|
|
597
|
-
// One-to-Many: User has many Books
|
|
598
|
-
this.hasMany(models.BookModel, {
|
|
599
|
-
foreignKey: 'userId'
|
|
600
|
-
});
|
|
601
|
-
}
|
|
602
|
-
```
|
|
603
|
-
|
|
604
|
-
For comprehensive model documentation and advanced features, see the [Model API Reference](https://takuya-motoshima.github.io/express-sweet/modules/database.html).
|
|
605
|
-
|
|
606
|
-
## View System
|
|
607
|
-
|
|
608
|
-
EXPRESS SWEET uses Handlebars as its template engine with automatic layout support and a rich set of custom helpers.
|
|
609
|
-
|
|
610
|
-
### Layout Usage
|
|
611
|
-
|
|
612
|
-
There are three ways to specify a layout, listed in order of precedence:
|
|
613
|
-
|
|
614
|
-
1. **Declarative within a page** using Handlebars comments:
|
|
615
|
-
```handlebars
|
|
616
|
-
{{!< LAYOUT}}
|
|
617
|
-
```
|
|
618
|
-
|
|
619
|
-
2. **As an option to render**:
|
|
620
|
-
```js
|
|
621
|
-
res.render('veggies', {
|
|
622
|
-
title: 'My favorite veggies',
|
|
623
|
-
veggies: veggies,
|
|
624
|
-
layout: 'layout/veggie'
|
|
625
|
-
});
|
|
626
|
-
```
|
|
627
|
-
|
|
628
|
-
To suppress layout rendering:
|
|
629
|
-
```js
|
|
630
|
-
res.render('veggies', {
|
|
631
|
-
title: 'My favorite veggies',
|
|
632
|
-
veggies: veggies,
|
|
633
|
-
layout: null // render without using a layout template
|
|
634
|
-
});
|
|
635
|
-
```
|
|
636
|
-
|
|
637
|
-
3. **Default layout** using `default_layout` specified in view configuration.
|
|
638
|
-
|
|
639
|
-
### Template Syntax
|
|
640
|
-
|
|
641
|
-
**Mark where layout should insert page content:**
|
|
642
|
-
```handlebars
|
|
643
|
-
{{{body}}}
|
|
644
|
-
```
|
|
645
|
-
|
|
646
|
-
**Declare a block placeholder in layout:**
|
|
647
|
-
```handlebars
|
|
648
|
-
{{{block "script"}}}
|
|
649
|
-
```
|
|
650
|
-
|
|
651
|
-
**Define block content in a page:**
|
|
652
|
-
```handlebars
|
|
653
|
-
{{#contentFor "script"}}
|
|
654
|
-
<script src="/js/page-specific.js"></script>
|
|
655
|
-
{{/contentFor}}
|
|
656
|
-
```
|
|
657
|
-
|
|
658
|
-
### Handlebars Helpers
|
|
659
|
-
|
|
660
|
-
EXPRESS SWEET provides a comprehensive collection of custom helpers for common template operations:
|
|
661
|
-
|
|
662
|
-
#### Array Helpers
|
|
663
|
-
|
|
664
|
-
Work with arrays and objects within arrays:
|
|
665
|
-
|
|
666
|
-
```handlebars
|
|
667
|
-
{{!-- Find object in array by property --}}
|
|
668
|
-
{{#each items}}
|
|
669
|
-
{{#if (eq id 123)}}
|
|
670
|
-
{{lookup (findObjectInArray ../items 'id' id) 'name'}}
|
|
671
|
-
{{/if}}
|
|
672
|
-
{{/each}}
|
|
673
|
-
```
|
|
674
|
-
|
|
675
|
-
#### Comparison Helpers
|
|
676
|
-
|
|
677
|
-
Perform logical and comparison operations:
|
|
678
|
-
|
|
679
|
-
```handlebars
|
|
680
|
-
{{!-- Equality checks --}}
|
|
681
|
-
{{#if (eq status 'active')}}Active User{{/if}}
|
|
682
|
-
|
|
683
|
-
{{!-- Numerical comparisons --}}
|
|
684
|
-
{{#if (gt score 90)}}Excellent Score{{/if}}
|
|
685
|
-
{{#if (lt age 18)}}Minor{{/if}}
|
|
686
|
-
|
|
687
|
-
{{!-- Logical operations --}}
|
|
688
|
-
{{#if (and isLoggedIn hasPermission)}}Show Protected Content{{/if}}
|
|
689
|
-
{{#if (or isAdmin isModerator)}}Show Admin Controls{{/if}}
|
|
690
|
-
|
|
691
|
-
{{!-- Empty/existence checks --}}
|
|
692
|
-
{{#if (empty comments)}}No comments yet{{/if}}
|
|
693
|
-
{{#if (includes roles 'admin')}}Admin Access{{/if}}
|
|
694
|
-
```
|
|
695
|
-
|
|
696
|
-
#### HTML Helpers
|
|
697
|
-
|
|
698
|
-
HTML and asset management utilities:
|
|
699
|
-
|
|
700
|
-
```handlebars
|
|
701
|
-
{{!-- Cache busting for static assets --}}
|
|
702
|
-
<link rel="stylesheet" href="{{cacheBusting '/css/style.css'}}">
|
|
703
|
-
<script src="{{cacheBusting '/js/app.js'}}"></script>
|
|
704
|
-
|
|
705
|
-
{{!-- Strip HTML tags from content --}}
|
|
706
|
-
{{{stripTags '<p>Hello <strong>World</strong></p>'}}} {{!-- Results: Hello World --}}
|
|
707
|
-
```
|
|
708
|
-
|
|
709
|
-
#### Object Helpers
|
|
710
|
-
|
|
711
|
-
JSON serialization and parsing:
|
|
712
|
-
|
|
713
|
-
```handlebars
|
|
714
|
-
{{!-- Convert objects to JSON strings --}}
|
|
715
|
-
<script>
|
|
716
|
-
var userData = {{{jsonStringify user}}};
|
|
717
|
-
var config = {{{jsonStringify appConfig}}};
|
|
718
|
-
</script>
|
|
719
|
-
|
|
720
|
-
{{!-- Parse JSON strings back to objects --}}
|
|
721
|
-
{{#with (jsonParse jsonString)}}
|
|
722
|
-
<h1>{{name}}</h1>
|
|
723
|
-
<p>{{email}}</p>
|
|
724
|
-
{{/with}}
|
|
725
|
-
```
|
|
726
|
-
|
|
727
|
-
#### String Helpers
|
|
728
|
-
|
|
729
|
-
String manipulation and formatting:
|
|
730
|
-
|
|
731
|
-
```handlebars
|
|
732
|
-
{{!-- String replacement --}}
|
|
733
|
-
<h1>{{replace title 'Draft' 'Published'}}</h1>
|
|
734
|
-
|
|
735
|
-
{{!-- Split strings into arrays --}}
|
|
736
|
-
{{#each (split tags ',')}}
|
|
737
|
-
<span class="tag">{{trim this}}</span>
|
|
738
|
-
{{/each}}
|
|
739
|
-
|
|
740
|
-
{{!-- Format file sizes --}}
|
|
741
|
-
<p>File size: {{formatBytes fileSize 2}}</p>
|
|
742
|
-
{{!-- Example output: File size: 1.23 MB --}}
|
|
743
|
-
```
|
|
744
|
-
|
|
745
|
-
#### Date Helpers
|
|
746
|
-
|
|
747
|
-
Date and time formatting with internationalization support:
|
|
748
|
-
|
|
749
|
-
```handlebars
|
|
750
|
-
{{!-- Format dates with custom patterns --}}
|
|
751
|
-
<p>Created: {{formatDate 'YYYY/MM/DD' createdAt}}</p>
|
|
752
|
-
<p>Time: {{formatDate 'HH:mm:ss' timestamp}}</p>
|
|
753
|
-
|
|
754
|
-
{{!-- Localized date formatting --}}
|
|
755
|
-
<p>Date: {{formatDate 'MMMM Do, YYYY' publishedAt 'en-US'}}</p>
|
|
756
|
-
<p>日付: {{formatDate 'YYYY年MM月DD日' publishedAt 'ja-JP'}}</p>
|
|
757
|
-
```
|
|
758
|
-
|
|
759
|
-
#### Number Helpers
|
|
760
|
-
|
|
761
|
-
Number formatting with locale support:
|
|
171
|
+
import UserModel from '../models/UserModel.js';
|
|
762
172
|
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
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 } });
|
|
768
178
|
```
|
|
769
179
|
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
Mathematical operations for template calculations:
|
|
180
|
+
### Transactions
|
|
773
181
|
|
|
774
|
-
```
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
<p>Rounded down: {{floor 4.7}}</p> {{!-- Results: 4 --}}
|
|
784
|
-
<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
|
+
}
|
|
785
191
|
```
|
|
786
192
|
|
|
787
|
-
|
|
193
|
+
Full reference (associations, raw queries, operators) → [docs/database.md](docs/database.md)
|
|
788
194
|
|
|
789
195
|
## Authentication
|
|
790
196
|
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
**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.
|
|
794
198
|
|
|
795
|
-
###
|
|
796
|
-
|
|
797
|
-
#### Asynchronous Login (Ajax)
|
|
798
|
-
|
|
799
|
-
Returns the authentication result for frontend processing:
|
|
199
|
+
### Config
|
|
800
200
|
|
|
801
201
|
```js
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
<label>Password</label>
|
|
820
|
-
<input type="password" name="password" required>
|
|
821
|
-
<button type="submit">Login</button>
|
|
822
|
-
</form>
|
|
823
|
-
|
|
824
|
-
<script>
|
|
825
|
-
const form = document.querySelector('#loginForm');
|
|
826
|
-
form.addEventListener('submit', async event => {
|
|
827
|
-
event.preventDefault();
|
|
828
|
-
|
|
829
|
-
const res = await fetch('/api/users/login', {
|
|
830
|
-
method: 'POST',
|
|
831
|
-
body: new FormData(form)
|
|
832
|
-
});
|
|
833
|
-
|
|
834
|
-
const isAuthenticated = await res.json();
|
|
835
|
-
if (!isAuthenticated) {
|
|
836
|
-
alert('The username or password is incorrect.');
|
|
837
|
-
return;
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
location.href = '/dashboard';
|
|
841
|
-
});
|
|
842
|
-
</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
|
+
};
|
|
843
219
|
```
|
|
844
220
|
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
Redirects based on authentication result:
|
|
221
|
+
### Login / Logout
|
|
848
222
|
|
|
849
223
|
```js
|
|
850
|
-
import {Router} from 'express';
|
|
224
|
+
import { Router } from 'express';
|
|
851
225
|
import * as expx from 'express-sweet';
|
|
852
226
|
|
|
853
227
|
const router = Router();
|
|
854
|
-
router.post('/login', async (req, res, next) => {
|
|
855
|
-
const isAuthenticated = await expx.services.Authentication.authenticate(req, res, next);
|
|
856
|
-
|
|
857
|
-
if (isAuthenticated) {
|
|
858
|
-
await expx.services.Authentication.successRedirect(res);
|
|
859
|
-
} else {
|
|
860
|
-
await expx.services.Authentication.failureRedirect(req, res);
|
|
861
|
-
}
|
|
862
|
-
});
|
|
863
|
-
|
|
864
|
-
export default router;
|
|
865
|
-
```
|
|
866
|
-
|
|
867
|
-
**Frontend HTML example:**
|
|
868
|
-
```html
|
|
869
|
-
<form method="post" action="/api/users/login">
|
|
870
|
-
<label>Email</label>
|
|
871
|
-
<input type="email" name="email" required autofocus>
|
|
872
|
-
<label>Password</label>
|
|
873
|
-
<input type="password" name="password" required>
|
|
874
|
-
<button type="submit">Login</button>
|
|
875
|
-
</form>
|
|
876
|
-
```
|
|
877
|
-
|
|
878
|
-
### Logout Example
|
|
879
|
-
|
|
880
|
-
To log out a user, call the `services.Authentication.logout()` method. This removes the `req.user` property and clears the login session:
|
|
881
228
|
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
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
|
+
});
|
|
885
233
|
|
|
886
|
-
const router = Router();
|
|
887
234
|
router.get('/logout', (req, res) => {
|
|
888
|
-
expx.
|
|
889
|
-
res.redirect('/
|
|
235
|
+
expx.Authentication.logout(req);
|
|
236
|
+
res.redirect('/');
|
|
890
237
|
});
|
|
891
238
|
|
|
892
239
|
export default router;
|
|
893
240
|
```
|
|
894
241
|
|
|
895
|
-
|
|
896
|
-
```html
|
|
897
|
-
<a href="/api/users/logout">Logout</a>
|
|
898
|
-
```
|
|
242
|
+
Full reference (Redis sessions, redirect helpers, route protection flow) → [docs/authentication.md](docs/authentication.md)
|
|
899
243
|
|
|
900
|
-
|
|
244
|
+
## Routing
|
|
901
245
|
|
|
902
|
-
|
|
246
|
+
Express Sweet uses **file-based routing**. Files in the `routes/` directory are automatically mapped to URL endpoints:
|
|
903
247
|
|
|
904
|
-
|
|
248
|
+
```
|
|
249
|
+
routes/
|
|
250
|
+
home.js → /home
|
|
251
|
+
about.js → /about
|
|
252
|
+
api/
|
|
253
|
+
users.js → /api/users
|
|
254
|
+
posts.js → /api/posts
|
|
255
|
+
```
|
|
905
256
|
|
|
906
|
-
|
|
257
|
+
Each route file exports an Express `Router`:
|
|
907
258
|
|
|
908
259
|
```js
|
|
909
|
-
|
|
910
|
-
import
|
|
911
|
-
|
|
260
|
+
// routes/api/users.js
|
|
261
|
+
import { Router } from 'express';
|
|
912
262
|
const router = Router();
|
|
913
263
|
|
|
914
|
-
|
|
915
|
-
router.get('
|
|
916
|
-
|
|
917
|
-
const books = await BookModel.findAll({
|
|
918
|
-
order: [['created', 'DESC']],
|
|
919
|
-
include: ['UserModel']
|
|
920
|
-
});
|
|
921
|
-
|
|
922
|
-
res.json({ books });
|
|
923
|
-
} catch (error) {
|
|
924
|
-
next(error);
|
|
925
|
-
}
|
|
926
|
-
});
|
|
927
|
-
|
|
928
|
-
// POST /api/books - Create a new book
|
|
929
|
-
router.post('/books', async (req, res, next) => {
|
|
930
|
-
try {
|
|
931
|
-
const { title, userId } = req.body;
|
|
932
|
-
|
|
933
|
-
const newBook = await BookModel.create({
|
|
934
|
-
title,
|
|
935
|
-
userId: userId || req.user.id
|
|
936
|
-
});
|
|
937
|
-
|
|
938
|
-
res.status(201).json({
|
|
939
|
-
success: true,
|
|
940
|
-
book: newBook
|
|
941
|
-
});
|
|
942
|
-
} catch (error) {
|
|
943
|
-
next(error);
|
|
944
|
-
}
|
|
945
|
-
});
|
|
946
|
-
|
|
947
|
-
// PUT /api/books/:id - Update a book
|
|
948
|
-
router.put('/books/:id', async (req, res, next) => {
|
|
949
|
-
try {
|
|
950
|
-
const { title } = req.body;
|
|
951
|
-
const bookId = req.params.id;
|
|
952
|
-
|
|
953
|
-
const [updatedRows] = await BookModel.update(
|
|
954
|
-
{ title },
|
|
955
|
-
{ where: { id: bookId } }
|
|
956
|
-
);
|
|
957
|
-
|
|
958
|
-
if (updatedRows === 0) {
|
|
959
|
-
return res.status(404).json({
|
|
960
|
-
success: false,
|
|
961
|
-
message: 'Book not found'
|
|
962
|
-
});
|
|
963
|
-
}
|
|
964
|
-
|
|
965
|
-
const updatedBook = await BookModel.findByPk(bookId);
|
|
966
|
-
res.json({
|
|
967
|
-
success: true,
|
|
968
|
-
book: updatedBook
|
|
969
|
-
});
|
|
970
|
-
} catch (error) {
|
|
971
|
-
next(error);
|
|
972
|
-
}
|
|
973
|
-
});
|
|
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 }));
|
|
974
267
|
|
|
975
268
|
export default router;
|
|
976
269
|
```
|
|
977
270
|
|
|
978
|
-
|
|
271
|
+
Set `default_router: '/home'` in `config.js` to also mount that route on `/`.
|
|
979
272
|
|
|
980
|
-
|
|
273
|
+
Full reference → [docs/routing.md](docs/routing.md)
|
|
981
274
|
|
|
982
|
-
|
|
983
|
-
import {Router} from 'express';
|
|
984
|
-
import UserModel from '../models/UserModel.js';
|
|
985
|
-
import BookModel from '../models/BookModel.js';
|
|
275
|
+
## View Engine
|
|
986
276
|
|
|
987
|
-
|
|
277
|
+
Handlebars is pre-configured as the template engine. Express Sweet ships with 37 built-in helpers across 9 categories:
|
|
988
278
|
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
}
|
|
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` |
|
|
1002
291
|
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
});
|
|
1008
|
-
|
|
1009
|
-
res.render('profile', {
|
|
1010
|
-
title: `${user.name}'s Profile`,
|
|
1011
|
-
user,
|
|
1012
|
-
books: userBooks,
|
|
1013
|
-
layout: 'layout/profile'
|
|
1014
|
-
});
|
|
1015
|
-
} catch (error) {
|
|
1016
|
-
next(error);
|
|
1017
|
-
}
|
|
1018
|
-
});
|
|
1019
|
-
|
|
1020
|
-
// Render partial view without layout
|
|
1021
|
-
router.get('/api/partial/user-stats', async (req, res) => {
|
|
1022
|
-
try {
|
|
1023
|
-
const bookCount = await BookModel.count({
|
|
1024
|
-
where: { userId: req.user.id }
|
|
1025
|
-
});
|
|
1026
|
-
|
|
1027
|
-
res.render('partials/user-stats', {
|
|
1028
|
-
bookCount,
|
|
1029
|
-
layout: null
|
|
1030
|
-
});
|
|
1031
|
-
} catch (error) {
|
|
1032
|
-
next(error);
|
|
1033
|
-
}
|
|
1034
|
-
});
|
|
292
|
+
```handlebars
|
|
293
|
+
{{#if (eq role 'admin')}}
|
|
294
|
+
<span class="badge">Admin</span>
|
|
295
|
+
{{/if}}
|
|
1035
296
|
|
|
1036
|
-
|
|
297
|
+
{{formatDate 'YYYY/MM/DD' createdAt}}
|
|
298
|
+
{{number2locale price 'en-US'}}
|
|
299
|
+
{{add subtotal tax}}
|
|
1037
300
|
```
|
|
1038
301
|
|
|
1039
|
-
|
|
302
|
+
Full helper reference → [docs/view-engine.md](docs/view-engine.md)
|
|
1040
303
|
|
|
1041
|
-
|
|
304
|
+
## File Upload
|
|
1042
305
|
|
|
1043
|
-
|
|
1044
|
-
// config/config.js
|
|
1045
|
-
const isDevelopment = process.env.NODE_ENV === 'development';
|
|
1046
|
-
const isProduction = process.env.NODE_ENV === 'production';
|
|
306
|
+
Multer-based file upload with per-route middleware resolution.
|
|
1047
307
|
|
|
308
|
+
```js
|
|
309
|
+
// config/upload.js
|
|
1048
310
|
export default {
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
// Custom error handling
|
|
1054
|
-
hook_handle_error: (error, req, res, next) => {
|
|
1055
|
-
if (error.status === 404) {
|
|
1056
|
-
res.status(404).render('errors/404', {
|
|
1057
|
-
title: 'Page Not Found'
|
|
1058
|
-
});
|
|
1059
|
-
} else {
|
|
1060
|
-
if (isProduction) {
|
|
1061
|
-
console.error('Server Error:', error);
|
|
1062
|
-
}
|
|
1063
|
-
|
|
1064
|
-
res.status(500).render('errors/500', {
|
|
1065
|
-
title: 'Server Error',
|
|
1066
|
-
error: isDevelopment ? error : null
|
|
1067
|
-
});
|
|
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');
|
|
1068
315
|
}
|
|
316
|
+
return null;
|
|
1069
317
|
},
|
|
1070
|
-
|
|
1071
|
-
// Custom Ajax detection
|
|
1072
|
-
is_ajax: (req) => {
|
|
1073
|
-
return req.xhr ||
|
|
1074
|
-
req.path.startsWith('/api/') ||
|
|
1075
|
-
req.get('Accept')?.includes('application/json');
|
|
1076
|
-
}
|
|
1077
318
|
};
|
|
1078
319
|
```
|
|
1079
320
|
|
|
1080
|
-
|
|
321
|
+
Full reference (disk storage, multiple files, file filtering) → [docs/file-upload.md](docs/file-upload.md)
|
|
1081
322
|
|
|
1082
|
-
|
|
323
|
+
## Demo
|
|
1083
324
|
|
|
1084
|
-
|
|
1085
|
-
import {Router} from 'express';
|
|
1086
|
-
import UserModel from '../models/UserModel.js';
|
|
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. Three commands and you're running.
|
|
1087
326
|
|
|
1088
|
-
|
|
327
|
+
## Migration from v4
|
|
1089
328
|
|
|
1090
|
-
|
|
1091
|
-
router.post('/users', async (req, res, next) => {
|
|
1092
|
-
try {
|
|
1093
|
-
const { name, email, password } = req.body;
|
|
1094
|
-
|
|
1095
|
-
// Input validation
|
|
1096
|
-
if (!email || !email.includes('@')) {
|
|
1097
|
-
return res.status(400).json({
|
|
1098
|
-
success: false,
|
|
1099
|
-
message: 'Invalid email format'
|
|
1100
|
-
});
|
|
1101
|
-
}
|
|
1102
|
-
|
|
1103
|
-
if (!password || password.length < 6) {
|
|
1104
|
-
return res.status(400).json({
|
|
1105
|
-
success: false,
|
|
1106
|
-
message: 'Password must be at least 6 characters'
|
|
1107
|
-
});
|
|
1108
|
-
}
|
|
1109
|
-
|
|
1110
|
-
// Check if user already exists
|
|
1111
|
-
const existingUser = await UserModel.findOne({
|
|
1112
|
-
where: { email }
|
|
1113
|
-
});
|
|
1114
|
-
|
|
1115
|
-
if (existingUser) {
|
|
1116
|
-
return res.status(409).json({
|
|
1117
|
-
success: false,
|
|
1118
|
-
message: 'User already exists with this email'
|
|
1119
|
-
});
|
|
1120
|
-
}
|
|
1121
|
-
|
|
1122
|
-
// Create user
|
|
1123
|
-
const user = await UserModel.create({
|
|
1124
|
-
name,
|
|
1125
|
-
email,
|
|
1126
|
-
password
|
|
1127
|
-
});
|
|
1128
|
-
|
|
1129
|
-
res.status(201).json({
|
|
1130
|
-
success: true,
|
|
1131
|
-
user: {
|
|
1132
|
-
id: user.id,
|
|
1133
|
-
name: user.name,
|
|
1134
|
-
email: user.email
|
|
1135
|
-
}
|
|
1136
|
-
});
|
|
1137
|
-
|
|
1138
|
-
} catch (error) {
|
|
1139
|
-
next(error);
|
|
1140
|
-
}
|
|
1141
|
-
});
|
|
1142
|
-
|
|
1143
|
-
export default router;
|
|
1144
|
-
```
|
|
329
|
+
Upgrading from v4? See the migration guide → [docs/migration-v5.md](docs/migration-v5.md)
|
|
1145
330
|
|
|
1146
|
-
##
|
|
331
|
+
## Changelog
|
|
1147
332
|
|
|
1148
|
-
|
|
333
|
+
See [CHANGELOG.md](CHANGELOG.md) for the full release history.
|
|
1149
334
|
|
|
1150
335
|
## Author
|
|
1151
336
|
|
|
1152
|
-
**
|
|
337
|
+
**shumatsumonobu**
|
|
1153
338
|
|
|
1154
|
-
* [github/
|
|
1155
|
-
* [x/
|
|
339
|
+
* [github/shumatsumonobu](https://github.com/shumatsumonobu)
|
|
340
|
+
* [x/shumatsumonobu](https://x.com/shumatsumonobu)
|
|
1156
341
|
* [facebook/takuya.motoshima.7](https://www.facebook.com/takuya.motoshima.7)
|
|
1157
342
|
|
|
1158
343
|
## License
|
|
1159
344
|
|
|
1160
|
-
[MIT](LICENSE)
|
|
345
|
+
[MIT](LICENSE)
|