express-sweet 2.0.9 → 3.0.1
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 +69 -1
- package/README.md +1039 -2137
- package/configuration_sample/cjs/authentication.js +50 -15
- package/configuration_sample/cjs/config.js +38 -21
- package/configuration_sample/cjs/database.js +90 -4
- package/configuration_sample/cjs/logging.js +41 -0
- package/configuration_sample/cjs/view.js +19 -1
- package/configuration_sample/esm/authentication.js +48 -15
- package/configuration_sample/esm/config.js +39 -22
- package/configuration_sample/esm/database.js +90 -4
- package/configuration_sample/esm/logging.js +41 -0
- package/configuration_sample/esm/view.js +20 -2
- package/dist/build.cjs +8 -8
- package/dist/build.mjs +4 -4
- package/package.json +9 -4
- package/types/database/DatabaseManager.d.ts +95 -0
- package/types/database/Model.d.ts +183 -20
- package/types/database/index.d.ts +47 -3
- package/types/database/loadModels.d.ts +19 -4
- package/types/handlebars_helpers/array.d.ts +3 -1
- package/types/handlebars_helpers/comparison.d.ts +55 -19
- package/types/handlebars_helpers/date.d.ts +3 -1
- package/types/handlebars_helpers/html.d.ts +6 -2
- package/types/handlebars_helpers/index.d.ts +73 -9
- package/types/handlebars_helpers/layouts.d.ts +5 -1
- package/types/handlebars_helpers/math.d.ts +21 -7
- package/types/handlebars_helpers/number.d.ts +3 -1
- package/types/handlebars_helpers/object.d.ts +6 -2
- package/types/handlebars_helpers/string.d.ts +9 -3
- package/types/index.d.ts +92 -5
- package/types/interfaces/AuthenticationConfig.d.ts +38 -1
- package/types/interfaces/BasicConfig.d.ts +26 -1
- package/types/interfaces/DatabaseConfig.d.ts +45 -1
- package/types/interfaces/LoggingConfig.d.ts +49 -0
- package/types/interfaces/ViewConfig.d.ts +21 -2
- package/types/interfaces/index.d.ts +25 -11
- package/types/middlewares/Authentication.d.ts +43 -6
- package/types/middlewares/CORS.d.ts +23 -5
- package/types/middlewares/Environment.d.ts +30 -4
- package/types/middlewares/ErrorHandler.d.ts +27 -5
- package/types/middlewares/Global.d.ts +20 -6
- package/types/middlewares/Http.d.ts +22 -5
- package/types/middlewares/Local.d.ts +35 -8
- package/types/middlewares/View.d.ts +39 -8
- package/types/middlewares/index.d.ts +47 -7
- package/types/mount.d.ts +16 -3
- package/types/routing/Router.d.ts +49 -7
- package/types/routing/index.d.ts +37 -1
- package/types/services/Authentication.d.ts +79 -16
- package/types/services/index.d.ts +33 -1
- package/types/types/global.d.ts +29 -8
- package/types/utils/Types.d.ts +5 -3
- package/types/utils/index.d.ts +71 -9
- package/types/utils/isArray.d.ts +12 -3
- package/types/utils/isAsyncFunction.d.ts +12 -5
- package/types/utils/isFunction.d.ts +13 -6
- package/types/utils/isObject.d.ts +14 -3
- package/types/utils/isString.d.ts +15 -4
- package/types/utils/loadAuthenticationConfig.d.ts +13 -3
- package/types/utils/loadBasicConfig.d.ts +13 -3
- package/types/utils/loadDatabaseConfig.d.ts +34 -3
- package/types/utils/loadLoggingConfig.d.ts +16 -0
- package/types/utils/loadViewConfig.d.ts +28 -3
- package/types/database/Database.d.ts +0 -18
- package/types/interfaces/BoundingBox.d.ts +0 -25
- package/types/interfaces/FaceDetails.d.ts +0 -30
- package/types/interfaces/FaceDetailsEmotions.d.ts +0 -40
- package/types/interfaces/FaceMatch.d.ts +0 -31
- package/types/interfaces/IndexFaceDetails.d.ts +0 -29
- package/types/interfaces/RekognitionOptions.d.ts +0 -26
- package/types/interfaces/SesOptions.d.ts +0 -27
package/README.md
CHANGED
|
@@ -1,1181 +1,566 @@
|
|
|
1
1
|
# EXPRESS SWEET
|
|
2
2
|
|
|
3
|
-
EXPRESS SWEET is a powerful Express.js extension that streamlines your workflow and boosts productivity with a suite of utilities and enhancements.
|
|
3
|
+
EXPRESS SWEET is a powerful Express.js extension that streamlines your development workflow and boosts productivity with a comprehensive suite of utilities and enhancements.
|
|
4
4
|
|
|
5
5
|
- [EXPRESS SWEET](#express-sweet)
|
|
6
|
+
- [Features](#features)
|
|
7
|
+
- [API Reference](#api-reference)
|
|
6
8
|
- [EXPRESS SWEET Generator](#express-sweet-generator)
|
|
7
|
-
- [
|
|
8
|
-
- [
|
|
9
|
-
- [
|
|
10
|
-
- [
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
- [
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
- [
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
- [
|
|
38
|
-
- [
|
|
39
|
-
- [
|
|
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)
|
|
40
54
|
- [Release Notes](#release-notes)
|
|
41
55
|
- [Author](#author)
|
|
42
56
|
- [License](#license)
|
|
43
57
|
|
|
58
|
+
## Features
|
|
59
|
+
|
|
60
|
+
EXPRESS SWEET provides the following key features to accelerate your development:
|
|
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
|
+
|
|
44
95
|
## EXPRESS SWEET Generator
|
|
96
|
+
|
|
45
97
|
Use the application generator tool, `express-sweet-generator`, to quickly create an application skeleton.
|
|
46
98
|
|
|
47
99
|

|
|
48
100
|
|
|
49
|
-
1. Install
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
1
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
},
|
|
160
|
-
production: {
|
|
161
|
-
username: 'root',
|
|
162
|
-
password: 'password',
|
|
163
|
-
database: 'sample_db',
|
|
164
|
-
host: 'localhost',
|
|
165
|
-
dialect: 'mariadb'
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
```
|
|
169
|
-
1. The DB to be accessed can be defined for each environment. Specify the environment in the `.env` file
|
|
170
|
-
```bash
|
|
171
|
-
NODE_ENV=development
|
|
172
|
-
```
|
|
173
|
-
1. Run the application with the following command.
|
|
174
|
-
```bash
|
|
175
|
-
npm start
|
|
176
|
-
```
|
|
177
|
-
1. Then, load `http://localhost:3000/` in your browser to access the app.
|
|
178
|
-
The generated app has the following directory structure:
|
|
179
|
-
```bash
|
|
180
|
-
.
|
|
181
|
-
├── .env
|
|
182
|
-
├── app.js
|
|
183
|
-
├── ecosystem.config.js
|
|
184
|
-
├── nginx.sample.conf
|
|
185
|
-
├── package.json
|
|
186
|
-
├── bin
|
|
187
|
-
│ └── www
|
|
188
|
-
├── client
|
|
189
|
-
│ ├── package.json
|
|
190
|
-
│ ├── webpack.config.js
|
|
191
|
-
│ └── src
|
|
192
|
-
├── config
|
|
193
|
-
│ ├── authentication.js
|
|
194
|
-
│ ├── config.js
|
|
195
|
-
│ ├── database.js
|
|
196
|
-
│ └── view.js
|
|
197
|
-
├── errors
|
|
198
|
-
│ └── UserNotFound.js
|
|
199
|
-
├── models
|
|
200
|
-
│ ├── BookModel.js
|
|
201
|
-
│ ├── CommentModel.js
|
|
202
|
-
│ ├── ProfileModel.js
|
|
203
|
-
│ └── UserModel.js
|
|
204
|
-
├── public
|
|
205
|
-
│ ├── build
|
|
206
|
-
│ └── upload
|
|
207
|
-
├── routes
|
|
208
|
-
│ ├── login.js
|
|
209
|
-
│ ├── users.js
|
|
210
|
-
│ └── api
|
|
211
|
-
│ └── users.js
|
|
212
|
-
├── shared
|
|
213
|
-
│ ├── CustomValidation.js
|
|
214
|
-
│ └── empty.js
|
|
215
|
-
└── views
|
|
216
|
-
├── edit-personal.hbs
|
|
217
|
-
├── error.hbs
|
|
218
|
-
├── login.hbs
|
|
219
|
-
├── personal.hbs
|
|
220
|
-
├── users.hbs
|
|
221
|
-
├── layout
|
|
222
|
-
│ └── default.hbs
|
|
223
|
-
└── partials
|
|
224
|
-
└── .gitkeep
|
|
225
|
-
```
|
|
226
|
-
|
|
227
|
-
## API
|
|
228
|
-
### Environment variable
|
|
229
|
-
If you set the environment variable file in env_path of `config/config.js`, the value of the environment variable file will be set automatically in process.env.
|
|
230
|
-
The `NODE_ENV` environment variable is required. If omitted, `development` is used.
|
|
231
|
-
You can access the environment variables yourself and perform your own checks and logic, as in the following example.
|
|
232
|
-
```js
|
|
233
|
-
if (process.env.NODE_ENV === 'development')
|
|
234
|
-
;
|
|
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
|
+
```
|
|
130
|
+
|
|
131
|
+
## Quick Start
|
|
132
|
+
|
|
133
|
+
### Database Setup
|
|
134
|
+
|
|
135
|
+
The application skeleton uses a MySQL/MariaDB database. Create a database with the following SQL:
|
|
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');
|
|
235
211
|
```
|
|
236
212
|
|
|
237
|
-
###
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
and [here](configuration_sample/cjs/config.js) to download a sample CJS configuration.
|
|
242
|
-
|
|
243
|
-
- `env_path: string`
|
|
244
|
-
The path to the environment configuration file (`.env`).
|
|
245
|
-
When you start the EXPRESS SWEET application, the contents of the environment configuration file are automatically read and saved in `process.env`.
|
|
246
|
-
The default is `.env`.
|
|
247
|
-
- `cors_enabled: boolean`
|
|
248
|
-
Set to true to allow requests from another domain to the application.
|
|
249
|
-
The default is `false`.
|
|
250
|
-
- `max_body_size: string|number`
|
|
251
|
-
Controls the maximum request body size.
|
|
252
|
-
If this is a number, then the value specifies the number of bytes.
|
|
253
|
-
if it is a string, the value is passed to the [bytes library](https://www.npmjs.com/package/bytes) for parsing.
|
|
254
|
-
The default is 100kb.
|
|
255
|
-
- `router_dir: string`
|
|
256
|
-
The directory path where the routes module is located.
|
|
257
|
-
The default is the `routes/` directory directly under the application root.
|
|
258
|
-
- `default_router: string`
|
|
259
|
-
EXPRESS SWEET can be told to load a default router when a URI is not present, as will be the case when root URL (`/`) is requested.
|
|
260
|
-
For example, to specify a default route, set `default_router` as follows.
|
|
261
|
-
Where blog is the name of the router module you want used.
|
|
262
|
-
Next, create the `routes/blog.js` module.
|
|
263
|
-
|
|
264
|
-
In the following example, requesting the root URL (`/`) will result in "Hello World".
|
|
265
|
-
```js
|
|
266
|
-
import {Router} from 'express';
|
|
267
|
-
|
|
268
|
-
const router = Router();
|
|
269
|
-
router.get('/', (req, res) => {
|
|
270
|
-
res.send('Hello World');
|
|
271
|
-
});
|
|
272
|
-
export default router;
|
|
273
|
-
```
|
|
274
|
-
- `rewrite_base_url: (baseUrl: string) => string`
|
|
275
|
-
This is a hook that rewrites the base URL.
|
|
276
|
-
If you want to rewrite the app.locals.baseUrl property and the view's baseUrl variable, use this hook to return a new base URL.
|
|
277
|
-
The default value is the referrer's origin (eg https://example.com).
|
|
278
|
-
In this example, `https://example.com/admin` is used as the base URL.
|
|
279
|
-
```js
|
|
280
|
-
rewrite_base_url: baseUrl => {
|
|
281
|
-
return `${baseUrl}/admin`;
|
|
282
|
-
}
|
|
283
|
-
```
|
|
284
|
-
- `is_ajax: (req: express.Request) => boolean`
|
|
285
|
-
How to determine if it is an ajax request.
|
|
286
|
-
The default is that if there is an XMLHttpRequest in the request header (`req.xhr`) returns `true`.
|
|
287
|
-
|
|
288
|
-
For example, if there is no XMLHttpRequest in req(`express.Request`) and the Ajax endpoint starts with /api, a custom Ajax decision can be made like `return /^\/api\//.test(req.path)`.
|
|
289
|
-
```js
|
|
290
|
-
is_ajax: req => {
|
|
291
|
-
// If the request URL begins with /api, it is assumed to be Ajax.
|
|
292
|
-
return /^\/api/.test(req.path);
|
|
293
|
-
// return !!req.xhr;
|
|
294
|
-
}
|
|
295
|
-
```
|
|
296
|
-
- `hook_handle_error: (error: any, req: express.Request, res: express.Response, next: express.NextFunction) => void`
|
|
297
|
-
Hooks the default behavior on request errors.
|
|
298
|
-
If unset, simply returns an error HTTP status. (`res.status(error.status||500).end();`)
|
|
299
|
-
```js
|
|
300
|
-
hook_handle_error: (error, req, res, next) => {
|
|
301
|
-
if (error.status === 404)
|
|
302
|
-
// If the URL cannot be found, a 404 error screen (views/error/404.hbs) is displayed.
|
|
303
|
-
res.render('error/404');
|
|
304
|
-
else
|
|
305
|
-
// For other errors, unknown error screen (views/error/500.hbs) is displayed.
|
|
306
|
-
res.render('error/500');
|
|
307
|
-
},
|
|
308
|
-
```
|
|
309
|
-
|
|
310
|
-
### Routing
|
|
311
|
-
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
|
|
312
|
-
Each route can have one or more handler functions, which are executed when the route is matched.
|
|
313
|
-
Route definition takes the following structure.
|
|
314
|
-
- app is an instance of express.
|
|
315
|
-
- METHOD is an [HTTP request method](https://en.wikipedia.org/wiki/HTTP#Request_methods), in lowercase.
|
|
316
|
-
- PATH is a path on the server.
|
|
317
|
-
- HANDLER is the function executed when the route is matched.
|
|
213
|
+
### Database Configuration
|
|
214
|
+
|
|
215
|
+
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).
|
|
216
|
+
|
|
318
217
|
```js
|
|
319
|
-
|
|
218
|
+
export default {
|
|
219
|
+
development: {
|
|
220
|
+
username: 'root',
|
|
221
|
+
password: 'password',
|
|
222
|
+
database: 'sample_db',
|
|
223
|
+
host: 'localhost',
|
|
224
|
+
dialect: 'mariadb'
|
|
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
|
+
```
|
|
242
|
+
|
|
243
|
+
### Environment Configuration
|
|
244
|
+
|
|
245
|
+
The database environment can be defined for each deployment stage. Specify the environment in the `.env` file:
|
|
246
|
+
|
|
247
|
+
```bash
|
|
248
|
+
NODE_ENV=development
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
### Running the Application
|
|
252
|
+
|
|
253
|
+
Start the application with the following command:
|
|
254
|
+
|
|
255
|
+
```bash
|
|
256
|
+
npm start
|
|
257
|
+
```
|
|
320
258
|
|
|
321
|
-
|
|
322
|
-
|
|
259
|
+
Then open `http://localhost:3000/` in your browser to access the application.
|
|
260
|
+
|
|
261
|
+
## Project Structure
|
|
262
|
+
|
|
263
|
+
The generated application has the following directory structure:
|
|
264
|
+
|
|
265
|
+
```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
|
|
323
312
|
```
|
|
324
313
|
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
314
|
+
### Key Directories Explained
|
|
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
|
|
332
|
+
|
|
333
|
+
EXPRESS SWEET uses several configuration files to customize application behavior. Each configuration file corresponds to a specific aspect of the framework:
|
|
334
|
+
|
|
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
|
+
```
|
|
347
|
+
|
|
348
|
+
### Base Configuration (`config/config.js`)
|
|
349
|
+
|
|
350
|
+
The core configuration of EXPRESS SWEET is defined in the `config/config.js` file.
|
|
351
|
+
|
|
352
|
+
**Sample configurations:**
|
|
353
|
+
- [ESM Configuration](configuration_sample/esm/config.js)
|
|
354
|
+
- [CJS Configuration](configuration_sample/cjs/config.js)
|
|
355
|
+
|
|
356
|
+
**Configuration Options:**
|
|
357
|
+
|
|
358
|
+
- **`env_path: string`**
|
|
359
|
+
Environment variable file (`.env`) path. Defaults to `undefined`.
|
|
360
|
+
When the EXPRESS SWEET application starts, the environment file contents are automatically loaded into `process.env`.
|
|
361
|
+
|
|
362
|
+
- **`cors_enabled: boolean`**
|
|
363
|
+
Enable CORS (Cross-Origin Resource Sharing). Defaults to `false`.
|
|
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:
|
|
330
440
|
```js
|
|
331
441
|
import {Router} from 'express';
|
|
332
442
|
|
|
333
443
|
const router = Router();
|
|
334
444
|
router.get('/', (req, res) => {
|
|
335
|
-
|
|
445
|
+
res.send('Hello World');
|
|
336
446
|
});
|
|
447
|
+
|
|
337
448
|
export default router;
|
|
338
449
|
```
|
|
339
450
|
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
451
|
+
### Nested Routing
|
|
452
|
+
|
|
453
|
+
The router supports nested folder structures. Nested files are automatically routed following the same path convention.
|
|
454
|
+
|
|
455
|
+
**Example:** `routes/api/users.js` responds to `GET /api/users` requests:
|
|
344
456
|
```js
|
|
345
457
|
import {Router} from 'express';
|
|
346
458
|
|
|
347
459
|
const router = Router();
|
|
348
460
|
router.get('/', (req, res) => {
|
|
349
|
-
|
|
461
|
+
res.send('Hello World');
|
|
350
462
|
});
|
|
463
|
+
|
|
351
464
|
export default router;
|
|
352
465
|
```
|
|
353
466
|
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
To specify a default router,
|
|
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:
|
|
470
|
+
|
|
357
471
|
```js
|
|
358
472
|
default_router: '/blog'
|
|
359
473
|
```
|
|
360
474
|
|
|
361
|
-
Where blog
|
|
362
|
-
|
|
475
|
+
Where `blog` corresponds to the router module name. Create the corresponding `routes/blog.js` module:
|
|
476
|
+
|
|
363
477
|
```js
|
|
364
478
|
import {Router} from 'express';
|
|
365
479
|
|
|
366
480
|
const router = Router();
|
|
367
481
|
router.get('/', (req, res) => {
|
|
368
|
-
|
|
482
|
+
res.send('Hello World');
|
|
369
483
|
});
|
|
484
|
+
|
|
370
485
|
export default router;
|
|
371
486
|
```
|
|
372
487
|
|
|
373
488
|
Now when you request the root URL (`/`), you will see "Hello World".
|
|
374
489
|
|
|
375
|
-
|
|
376
|
-
Express supports the following routing methods corresponding to the HTTP methods of the same names.
|
|
377
|
-
For more details about routing, see the [Exprees’s Routing Guide](https://expressjs.com/en/guide/routing.html#express-router).
|
|
378
|
-
- checkout
|
|
379
|
-
- copy
|
|
380
|
-
- delete
|
|
381
|
-
- get
|
|
382
|
-
- head
|
|
383
|
-
- lock
|
|
384
|
-
- merge
|
|
385
|
-
- mkactivity
|
|
386
|
-
- mkcol
|
|
387
|
-
- move
|
|
388
|
-
- m-search
|
|
389
|
-
- notify
|
|
390
|
-
- options
|
|
391
|
-
- patch
|
|
392
|
-
- post
|
|
393
|
-
- purge
|
|
394
|
-
- put
|
|
395
|
-
- report
|
|
396
|
-
- search
|
|
397
|
-
- subscribe
|
|
398
|
-
- trace
|
|
399
|
-
- unlock
|
|
400
|
-
- unsubscribe
|
|
401
|
-
|
|
402
|
-
### View
|
|
403
|
-
EXPRESS SWEET uses Handlebars as its view template engine.
|
|
404
|
-
This section describes the basic usage of the view on EXPRESS SWEET.
|
|
405
|
-
See the [here](https://handlebarsjs.com/guide/) for more information on how to use Handlebars.
|
|
406
|
-
|
|
407
|
-
#### Configuration
|
|
408
|
-
The view (template engine) configuration is defined in the `config/view.js` file.
|
|
409
|
-
|
|
410
|
-
Click [here](configuration_sample/esm/view.js) to download a sample ESM configuration
|
|
411
|
-
and [here](configuration_sample/cjs/view.js) to download a sample CJS configuration.
|
|
412
|
-
|
|
413
|
-
- `views_dir: string`
|
|
414
|
-
The directory path where the view will be placed.
|
|
415
|
-
The default is the `views/` directory directly under the application root.
|
|
416
|
-
- `partials_dir: string`
|
|
417
|
-
The directory path where the reusable templates are located.
|
|
418
|
-
The default is the `views/partials/` directory directly under the application root.
|
|
419
|
-
Reusable templates are automatically loaded when you launch the EXPRESS SWEET application and can be called from other templates.
|
|
420
|
-
- `layouts_dir: string`
|
|
421
|
-
The directory path where the reusable base template is located.
|
|
422
|
-
The default is the `views/layout/` directory directly under the application root.
|
|
423
|
-
- `default_layout: string`
|
|
424
|
-
The path to the layout file used by default.
|
|
425
|
-
The default is the `views/layout/default.*` File directly under the application root.
|
|
426
|
-
The extension of the default layout file is replaced with the extension specified by `extension`.
|
|
427
|
-
- `extension: string`
|
|
428
|
-
Extension for templates and partials files.
|
|
429
|
-
The default is `.hbs`.
|
|
430
|
-
- `beforeRender: (req: express.Request, res: express.Response) => Promise<void>|void`
|
|
431
|
-
Hook function just before the view is rendered.
|
|
432
|
-
For example, you can set your own local variables that can be used within the view.
|
|
433
|
-
```js
|
|
434
|
-
beforeRender: (req, res) => {
|
|
435
|
-
res.locals.extra = 'Extra';
|
|
436
|
-
}
|
|
437
|
-
```
|
|
490
|
+
### Routing Methods
|
|
438
491
|
|
|
439
|
-
|
|
440
|
-
To mark where layout should insert page.
|
|
441
|
-
```js
|
|
442
|
-
{{{body}}}
|
|
443
|
-
```
|
|
492
|
+
Express supports routing methods corresponding to HTTP methods:
|
|
444
493
|
|
|
445
|
-
|
|
446
|
-
```js
|
|
447
|
-
{{{block "script"}}}
|
|
448
|
-
```
|
|
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`
|
|
449
495
|
|
|
450
|
-
|
|
451
|
-
```js
|
|
452
|
-
{{#contentFor "script"}}
|
|
453
|
-
CONTENT HERE
|
|
454
|
-
{{/contentFor}}
|
|
455
|
-
```
|
|
496
|
+
For comprehensive routing documentation, see the [Express Routing Guide](https://expressjs.com/en/guide/routing.html#express-router).
|
|
456
497
|
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
1. Declarative within a page. Use handlebars comment.
|
|
461
|
-
```js
|
|
462
|
-
{{!< LAYOUT}}
|
|
463
|
-
```
|
|
464
|
-
|
|
465
|
-
Layout file resolution.
|
|
466
|
-
```js
|
|
467
|
-
If path starts with '.'
|
|
468
|
-
LAYOUT is relative to template
|
|
469
|
-
Else If `layoutsDir` is set
|
|
470
|
-
LAYOUT is relative to `layoutsDir`
|
|
471
|
-
Else
|
|
472
|
-
LAYOUT from path.resolve(dirname(template), LAYOUT)
|
|
473
|
-
```
|
|
474
|
-
1. As an option to render.
|
|
475
|
-
Do not use this option in conjunction with passing user submitted data to res.
|
|
476
|
-
render e.g. res.render('index', req.query).
|
|
477
|
-
This allows users to read arbitrary files from your filesystem.
|
|
478
|
-
```js
|
|
479
|
-
res.render('veggies', {
|
|
480
|
-
title: 'My favorite veggies',
|
|
481
|
-
veggies: veggies,
|
|
482
|
-
layout: 'layout/veggie'
|
|
483
|
-
});
|
|
484
|
-
```
|
|
485
|
-
|
|
486
|
-
This option also allows for layout suppression (both the default layout and when specified declaratively in a page) by passing in a falsey Javascript value as the value of the layout property.
|
|
487
|
-
```js
|
|
488
|
-
res.render('veggies', {
|
|
489
|
-
title: 'My favorite veggies',
|
|
490
|
-
veggies: veggies,
|
|
491
|
-
layout: null // render without using a layout template
|
|
492
|
-
});
|
|
493
|
-
```
|
|
494
|
-
|
|
495
|
-
Layout file resolution.
|
|
496
|
-
```js
|
|
497
|
-
If path starts with '.'
|
|
498
|
-
layout is relative to template
|
|
499
|
-
Else If `layoutsDir` is set
|
|
500
|
-
layout is relative to `layoutsDir`
|
|
501
|
-
Else
|
|
502
|
-
layout from path.resolve(viewsDir, layout)
|
|
503
|
-
```
|
|
504
|
-
1. Lastly, use defaultLayout if specified in hbs configuration options.
|
|
505
|
-
Layouts can be nested: just include a declarative layout tag within any layout template to have its content included in the declared "parent" layout.
|
|
506
|
-
Be aware that too much nesting can impact performances, and stay away from infinite loops.
|
|
507
|
-
|
|
508
|
-
#### Array Helper
|
|
509
|
-
- `findObjectInArray()`
|
|
510
|
-
Finds an object in an array based on the specified field name and value.
|
|
511
|
-
|
|
512
|
-
**Parameters:**
|
|
513
|
-
- array: Array<{[key: string]: any}>
|
|
514
|
-
The array of objects to search.
|
|
515
|
-
- fieldName: string
|
|
516
|
-
The name of the field to search.
|
|
517
|
-
- fieldValue: any
|
|
518
|
-
fieldValue The value to search for.
|
|
519
|
-
|
|
520
|
-
**Return:**
|
|
521
|
-
`object|null` The first object in the array that matches the criteria, or null if no match is found.
|
|
522
|
-
|
|
523
|
-
```js
|
|
524
|
-
{{!--
|
|
525
|
-
items is an array of objects: [{id: 123, name: 'Item A'}, {id: 456, name: 'Item B'}]
|
|
526
|
-
This code will output: "Item A"
|
|
527
|
-
--}}
|
|
528
|
-
{{#each items}}
|
|
529
|
-
{{#if (eq id 123)}}
|
|
530
|
-
{{lookup (findObjectInArray ../items 'id' id) 'name'}}
|
|
531
|
-
{{/if}}
|
|
532
|
-
{{/each}}
|
|
533
|
-
```
|
|
534
|
-
|
|
535
|
-
#### Comparison Helper
|
|
536
|
-
- `eq()`
|
|
537
|
-
Determine whether or not two values are equal (===).
|
|
538
|
-
|
|
539
|
-
**Parameters:**
|
|
540
|
-
- val1: any
|
|
541
|
-
First value to be compared with second.
|
|
542
|
-
- val2: any
|
|
543
|
-
Second value to be compared with first.
|
|
544
|
-
|
|
545
|
-
**Return:**
|
|
546
|
-
`boolean` Returns true if the value and type are the same, false if they are different.
|
|
547
|
-
|
|
548
|
-
```js
|
|
549
|
-
{{eq val1 val2}}
|
|
550
|
-
{{#if (eqw val1 val2)}}...{{/if}}
|
|
551
|
-
```
|
|
552
|
-
- `eqw()`
|
|
553
|
-
Determine whether or not two values are equal (==) i.e. weak checking.
|
|
554
|
-
|
|
555
|
-
**Parameters:**
|
|
556
|
-
- val1: any
|
|
557
|
-
First value to be compared with second.
|
|
558
|
-
- val2: any
|
|
559
|
-
Second value to be compared with first.
|
|
560
|
-
|
|
561
|
-
**Return:**
|
|
562
|
-
`boolean` Returns true if the values are the same, false if they are different.
|
|
563
|
-
|
|
564
|
-
```js
|
|
565
|
-
{{eqw val1 val2}}
|
|
566
|
-
{{#if (eqw val1 val2)}}...{{/if}}
|
|
567
|
-
```
|
|
568
|
-
- `neq()`
|
|
569
|
-
Determine whether or not two values are not equal (!==).
|
|
570
|
-
|
|
571
|
-
**Parameters:**
|
|
572
|
-
- val1: any
|
|
573
|
-
First value to be compared with second.
|
|
574
|
-
- val2: any
|
|
575
|
-
Second value to be compared with first.
|
|
576
|
-
|
|
577
|
-
**Return:**
|
|
578
|
-
`boolean` Returns true if the value and type are different, false if they are the same.
|
|
579
|
-
|
|
580
|
-
```js
|
|
581
|
-
{{neq val1 val2}}
|
|
582
|
-
{{#if (neq val1 val2)}}...{{/if}}
|
|
583
|
-
```
|
|
584
|
-
- `neqw()`
|
|
585
|
-
Determine whether or not two values are not equal (!=) weak checking.
|
|
586
|
-
|
|
587
|
-
**Parameters:**
|
|
588
|
-
- val1: any
|
|
589
|
-
First value to be compared with second.
|
|
590
|
-
- val2: any
|
|
591
|
-
Second value to be compared with first.
|
|
592
|
-
|
|
593
|
-
**Return:**
|
|
594
|
-
`boolean` Returns true if the values are different, false if they are the same.
|
|
595
|
-
|
|
596
|
-
```js
|
|
597
|
-
{{neqw val1 val2}}
|
|
598
|
-
{{#if (neqw val1 val2)}}...{{/if}}
|
|
599
|
-
```
|
|
600
|
-
- `lt()`
|
|
601
|
-
Check for less than condition (`a < b`).
|
|
602
|
-
|
|
603
|
-
**Parameters:**
|
|
604
|
-
- val1: any
|
|
605
|
-
First value to be compared with second.
|
|
606
|
-
- val2: any
|
|
607
|
-
Second value to be compared with first.
|
|
608
|
-
|
|
609
|
-
**Return:**
|
|
610
|
-
`boolean` Returns true if the first value is less than the second value, false otherwise.
|
|
611
|
-
|
|
612
|
-
```js
|
|
613
|
-
{{lt val1 val2}}
|
|
614
|
-
{{#if (lt val1 val2)}}...{{/if}}
|
|
615
|
-
```
|
|
616
|
-
- `lte()`
|
|
617
|
-
Check for less than or equals condition (`a <= b`).
|
|
618
|
-
|
|
619
|
-
**Parameters:**
|
|
620
|
-
- val1: any
|
|
621
|
-
First value to be compared with second.
|
|
622
|
-
- val2: any
|
|
623
|
-
Second value to be compared with first.
|
|
624
|
-
|
|
625
|
-
**Return:**
|
|
626
|
-
`boolean` Returns true if the first value is less than or equal to the second value, false otherwise.
|
|
627
|
-
|
|
628
|
-
```js
|
|
629
|
-
{{lte val1 val2}}
|
|
630
|
-
{{#if (lte val1 val2)}}...{{/if}}
|
|
631
|
-
```
|
|
632
|
-
- `gt()`
|
|
633
|
-
Check for greater than condition (a > b).
|
|
634
|
-
|
|
635
|
-
**Parameters:**
|
|
636
|
-
- val1: any
|
|
637
|
-
First value to be compared with second.
|
|
638
|
-
- val2: any
|
|
639
|
-
Second value to be compared with first.
|
|
640
|
-
|
|
641
|
-
**Return:**
|
|
642
|
-
`boolean` Returns true if the first value exceeds the second value, false otherwise.
|
|
643
|
-
|
|
644
|
-
```js
|
|
645
|
-
{{gt val1 val2}}
|
|
646
|
-
{{#if (gt val1 val2)}}...{{/if}}
|
|
647
|
-
```
|
|
648
|
-
- `gte()`
|
|
649
|
-
Check for greater than or equals condition (a >= b).
|
|
650
|
-
|
|
651
|
-
**Parameters:**
|
|
652
|
-
- val1: any
|
|
653
|
-
First value to be compared with second.
|
|
654
|
-
- val2: any
|
|
655
|
-
Second value to be compared with first.
|
|
656
|
-
|
|
657
|
-
**Return:**
|
|
658
|
-
`boolean` Returns true if the first value is greater than or equal to the second value, false otherwise.
|
|
659
|
-
|
|
660
|
-
```js
|
|
661
|
-
{{gte val1 val2}}
|
|
662
|
-
{{#if (gte val1 val2)}}...{{/if}}
|
|
663
|
-
```
|
|
664
|
-
- `not()`
|
|
665
|
-
Logical NOT of any expression.
|
|
666
|
-
|
|
667
|
-
**Parameters:**
|
|
668
|
-
- val: any
|
|
669
|
-
Any expression.
|
|
670
|
-
|
|
671
|
-
**Return:**
|
|
672
|
-
`boolean` Returns the logical negation of the value.
|
|
673
|
-
|
|
674
|
-
```js
|
|
675
|
-
{{not val}}
|
|
676
|
-
{{#if (not (eq val1 val2))}}...{{/if}}
|
|
677
|
-
```
|
|
678
|
-
- `ifx()`
|
|
679
|
-
Helper to imitate the ternary `?:` conditional operator.
|
|
680
|
-
|
|
681
|
-
**Parameters:**
|
|
682
|
-
- condition: boolean
|
|
683
|
-
Satisfying condition for getting first value. Either true of false.
|
|
684
|
-
- val1: any
|
|
685
|
-
First value to be displayed as result.
|
|
686
|
-
- val2: any
|
|
687
|
-
Second value to be displayed as result. Defaults to an empty string.
|
|
688
|
-
|
|
689
|
-
**Return:**
|
|
690
|
-
`any` Returns the result of the ternary operator.
|
|
691
|
-
|
|
692
|
-
```js
|
|
693
|
-
{{ifx true val1 val2}}
|
|
694
|
-
{{ifx false val1 val2}}
|
|
695
|
-
{{ifx (eq val1 val2) val3 val4}}
|
|
696
|
-
{{ifx (not (eq val1 val2)) val3 val4}}
|
|
697
|
-
{{ifx true val}}
|
|
698
|
-
{{ifx false val}}
|
|
699
|
-
```
|
|
700
|
-
- `empty()`
|
|
701
|
-
Check if it is empty.
|
|
702
|
-
If the value is an array, returns true if there are no elements.
|
|
703
|
-
If the value is a string, the leading and trailing spaces are trimmed and then checked.
|
|
704
|
-
|
|
705
|
-
**Parameters:**
|
|
706
|
-
- value: any
|
|
707
|
-
Character strings, arrays, objects, etc. to be checked.
|
|
708
|
-
|
|
709
|
-
**Return:**
|
|
710
|
-
`boolean` Returns true if the value is empty, false otherwise.
|
|
711
|
-
|
|
712
|
-
```js
|
|
713
|
-
{{empty val}}
|
|
714
|
-
{{#if (empty val)}}...{{/if}}
|
|
715
|
-
```
|
|
716
|
-
- `notEmpty()`
|
|
717
|
-
Check that it is not empty.
|
|
718
|
-
If the value is an array, returns true if there is an element.
|
|
719
|
-
If the value is a string, the leading and trailing spaces are trimmed and then checked.
|
|
720
|
-
|
|
721
|
-
**Parameters:**
|
|
722
|
-
- val: any
|
|
723
|
-
Character strings, arrays, objects, etc. to be checked.
|
|
724
|
-
|
|
725
|
-
**Return:**
|
|
726
|
-
`boolean` Returns true if the value is not empty, false otherwise.
|
|
727
|
-
|
|
728
|
-
```js
|
|
729
|
-
{{notEmpty val}}
|
|
730
|
-
{{#if (notEmpty val)}}...{{/if}}
|
|
731
|
-
```
|
|
732
|
-
- `count()`
|
|
733
|
-
Determine the length of an array.
|
|
734
|
-
|
|
735
|
-
**Parameters:**
|
|
736
|
-
- items: any[]
|
|
737
|
-
Array whose elements to be counted.
|
|
738
|
-
|
|
739
|
-
**Return:**
|
|
740
|
-
`number|false` Returns the length of the array if the value is an array, false if the value is not an array.
|
|
741
|
-
|
|
742
|
-
```js
|
|
743
|
-
{{count val}}
|
|
744
|
-
```
|
|
745
|
-
- `and()`
|
|
746
|
-
Returns the boolean AND of two or more parameters passed i.e it is true iff all the parameters are true.
|
|
747
|
-
|
|
748
|
-
**Parameters:**
|
|
749
|
-
- ...params: any[]
|
|
750
|
-
Any number of boolean parameters.
|
|
751
|
-
|
|
752
|
-
**Return:**
|
|
753
|
-
`boolean` Returns the result of the logical product.
|
|
754
|
-
|
|
755
|
-
```js
|
|
756
|
-
{{and val1 val2}}
|
|
757
|
-
{{#if (and val1 val2)}}...{{/if}}
|
|
758
|
-
```
|
|
759
|
-
- `or()`
|
|
760
|
-
Returns the boolean OR of two or more parameters passed i.e it is true if any of the parameters is true.
|
|
761
|
-
|
|
762
|
-
**Parameters:**
|
|
763
|
-
- ...params: any[]
|
|
764
|
-
Any number of boolean parameters.
|
|
765
|
-
|
|
766
|
-
**Return:**
|
|
767
|
-
`boolean` Returns the result of the OR.
|
|
768
|
-
|
|
769
|
-
```js
|
|
770
|
-
{{or val1 val2}}
|
|
771
|
-
{{#if (or val1 val2)}}...{{/if}}
|
|
772
|
-
```
|
|
773
|
-
- `coalesce()`
|
|
774
|
-
Returns the first non-falsy value from the parameter list.
|
|
775
|
-
Works quite similar to the SQL's `COALESCE()` function, but unlike this checks for the first non-false parameter.
|
|
776
|
-
|
|
777
|
-
**Parameters:**
|
|
778
|
-
- ...params: any[]
|
|
779
|
-
Any number of parameters.
|
|
780
|
-
|
|
781
|
-
**Return:**
|
|
782
|
-
`any` Returns the first non-false element of the parameter.
|
|
783
|
-
|
|
784
|
-
```js
|
|
785
|
-
{{coalesce val1 val2}}
|
|
786
|
-
```
|
|
787
|
-
- `includes()`
|
|
788
|
-
Returns boolean if the array contains the element strictly or non-strictly.
|
|
789
|
-
|
|
790
|
-
**Parameters:**
|
|
791
|
-
- items: any[]
|
|
792
|
-
The array.
|
|
793
|
-
- val: any
|
|
794
|
-
The value to be checked for existence in the array.
|
|
795
|
-
- strict: boolean
|
|
796
|
-
`false` for non-strict checking. `true` by default.
|
|
797
|
-
|
|
798
|
-
**Return:**
|
|
799
|
-
`boolean` Returns true if the array contains the specified value, false otherwise.
|
|
800
|
-
|
|
801
|
-
```js
|
|
802
|
-
{{includes [1, 2, 3] 2}}
|
|
803
|
-
{{includes [1, 2, 3] 2 true}}
|
|
804
|
-
{{#if (includes [1, 2, 3] 2)}}...{{/if}}
|
|
805
|
-
{{ifx (includes [1, 2, 3] 2) true false}}
|
|
806
|
-
```
|
|
807
|
-
- `regexMatch()`
|
|
808
|
-
Returns true if the given str matches the given regex.
|
|
809
|
-
|
|
810
|
-
**Parameters:**
|
|
811
|
-
- val: string
|
|
812
|
-
The string against which to match the regular expression.
|
|
813
|
-
- pattern: string
|
|
814
|
-
The text of the regular expression.
|
|
815
|
-
- flags?: string
|
|
816
|
-
Regular expression flags, such as global and case-insensitive searches. The default is none (undefined).
|
|
817
|
-
|
|
818
|
-
**Return:**
|
|
819
|
-
`boolean` true if there is a match between the regular expression and the string str. Otherwise, false.
|
|
820
|
-
|
|
821
|
-
```js
|
|
822
|
-
{{regexMatch 'Hello, world!' 'Hello'}}
|
|
823
|
-
{{regexMatch 'Hello, world!' 'Hello' 'i'}}
|
|
824
|
-
{{#if (regexMatch 'Hello, world!' 'Hello')}}...{{/if}}
|
|
825
|
-
```
|
|
826
|
-
|
|
827
|
-
#### HTML Helper
|
|
828
|
-
- `cacheBusting()`
|
|
829
|
-
Returns the Assets path containing the file update time parameter.
|
|
830
|
-
|
|
831
|
-
**Parameters:**
|
|
832
|
-
- filePath: string
|
|
833
|
-
Paths of Assets files such as CSS and JS in public directories.
|
|
834
|
-
- baseUrl: string
|
|
835
|
-
Application Origin URL. The default is none (`undefined`).
|
|
836
|
-
|
|
837
|
-
**Return:**
|
|
838
|
-
`string` Returns the Assets file path with the update date and time parameters.
|
|
839
|
-
|
|
840
|
-
```js
|
|
841
|
-
{{!-- results in: example.com/assets/style.css?1620526340463 --}}
|
|
842
|
-
{{cacheBusting '/assets/style.css' '//example.com'}}
|
|
843
|
-
```
|
|
844
|
-
|
|
845
|
-
- `stripTags()`
|
|
846
|
-
Removes HTML tags from a string, optionally allowing specific tags.
|
|
847
|
-
|
|
848
|
-
**Parameters:**
|
|
849
|
-
- str: string
|
|
850
|
-
The string to remove HTML tags from.
|
|
851
|
-
- allowedTags: string|string[]
|
|
852
|
-
An array of allowed HTML tags. Default is an empty array.
|
|
853
|
-
- replacement: string
|
|
854
|
-
The string to replace HTML tags with. Default is blank.
|
|
855
|
-
|
|
856
|
-
**Return:**
|
|
857
|
-
`string` The string with HTML tags removed.
|
|
858
|
-
|
|
859
|
-
```js
|
|
860
|
-
{{!-- results in: lorem ipsum dolor sit amet --}}
|
|
861
|
-
{{{stripTags '<a href="https://example.com">lorem ipsum <strong>dolor</strong> <em>sit</em> amet</a>'}}}
|
|
862
|
-
|
|
863
|
-
{{!-- results in: lorem ipsum <strong>dolor</strong> sit amet --}}
|
|
864
|
-
{{{stripTags '<a href="https://example.com">lorem ipsum <strong>dolor</strong> <em>sit</em> amet</a>' '<strong>' ''}}}
|
|
865
|
-
|
|
866
|
-
{{!-- results in: 🍩lorem ipsum 🍩dolor🍩 🍩sit🍩 amet🍩 --}}
|
|
867
|
-
{{{stripTags '<a href="https://example.com">lorem ipsum <strong>dolor</strong> <em>sit</em> amet</a>' [] '🍩'}}}
|
|
868
|
-
```
|
|
869
|
-
|
|
870
|
-
#### Object Helper
|
|
871
|
-
- `jsonStringify()`
|
|
872
|
-
Stringify an object using JSON.stringify.
|
|
873
|
-
|
|
874
|
-
**Parameters:**
|
|
875
|
-
- val: any
|
|
876
|
-
The value to convert to a JSON string.
|
|
877
|
-
- indent: number
|
|
878
|
-
The number of space characters to use as whitespace.
|
|
879
|
-
|
|
880
|
-
**Return:**
|
|
881
|
-
`string` A JSON string representing the given value, or undefined.
|
|
882
|
-
|
|
883
|
-
```js
|
|
884
|
-
{{jsonStringify val}}
|
|
885
|
-
```
|
|
886
|
-
- `jsonParse()`
|
|
887
|
-
Parses the given string using JSON.parse.
|
|
888
|
-
|
|
889
|
-
**Parameters:**
|
|
890
|
-
- val: any
|
|
891
|
-
Object to stringify.
|
|
892
|
-
|
|
893
|
-
**Return:**
|
|
894
|
-
`any` JavaScript value or object described by a string.
|
|
895
|
-
|
|
896
|
-
```js
|
|
897
|
-
{{jsonParse val}}
|
|
898
|
-
```
|
|
899
|
-
|
|
900
|
-
#### String Helper
|
|
901
|
-
- `replace()`
|
|
902
|
-
Returns a new string with some or all matches of a pattern replaced by a replacement.
|
|
903
|
-
|
|
904
|
-
**Parameters:**
|
|
905
|
-
- val: string
|
|
906
|
-
String.
|
|
907
|
-
- find: string
|
|
908
|
-
The string to be replaced.
|
|
909
|
-
- replace: string
|
|
910
|
-
The string to replace.
|
|
911
|
-
|
|
912
|
-
**Return:**
|
|
913
|
-
`string` Character string after replacement.
|
|
914
|
-
|
|
915
|
-
```js
|
|
916
|
-
{{replace 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?' 'dog' 'monkey'}}
|
|
917
|
-
```
|
|
918
|
-
- `split()`
|
|
919
|
-
Split `string` by the given `character`.
|
|
920
|
-
|
|
921
|
-
**Parameters:**
|
|
922
|
-
- val: string
|
|
923
|
-
String.
|
|
924
|
-
- separator: string
|
|
925
|
-
A character that delimits the substrings in this string. Default is a comma.
|
|
926
|
-
|
|
927
|
-
**Return:**
|
|
928
|
-
`string[]` An Array of strings, split at each point where the separator occurs in the given string. The default is a comma.
|
|
929
|
-
|
|
930
|
-
```js
|
|
931
|
-
{{split "a,b,c" ","}}
|
|
932
|
-
{{#each (split list ',')}}<div>{{this}}</div>{{/each}}
|
|
933
|
-
```
|
|
934
|
-
- `formatBytes()`
|
|
935
|
-
Convert bytes to just the right units(KB, MB, GB, TB, PB, EB, ZB, YB).
|
|
936
|
-
|
|
937
|
-
**Parameters:**
|
|
938
|
-
- bytes: number
|
|
939
|
-
Bytes.
|
|
940
|
-
- decimals?: number
|
|
941
|
-
Number of decimal places to display. Default is 0.
|
|
942
|
-
|
|
943
|
-
**Return:**
|
|
944
|
-
`string` Returns a value with units.
|
|
945
|
-
|
|
946
|
-
```js
|
|
947
|
-
{{!-- results in: 1 KB --}}
|
|
948
|
-
{{formatBytes 1024}}
|
|
949
|
-
|
|
950
|
-
{{!-- results in: 1.21 KB --}}
|
|
951
|
-
{{formatBytes 1234 2}}
|
|
952
|
-
|
|
953
|
-
{{!-- results in: 1.205 KB --}}
|
|
954
|
-
{{formatBytes 1234 3}}
|
|
955
|
-
|
|
956
|
-
{{!-- results in: 0 Bytes --}}
|
|
957
|
-
{{formatBytes 0}}
|
|
958
|
-
```
|
|
959
|
-
|
|
960
|
-
#### Date Helper
|
|
961
|
-
- `formatDate()`
|
|
962
|
-
Use moment to format the date.
|
|
963
|
-
|
|
964
|
-
**Parameters:**
|
|
965
|
-
- format: string
|
|
966
|
-
A format string based on `moment`.
|
|
967
|
-
- date: string
|
|
968
|
-
Date string to format.
|
|
969
|
-
- locale: string|string[]
|
|
970
|
-
Language or language-country locale string (or array of strings) available in [https://github.com/moment/moment/tree/develop/locale](https://github.com/moment/moment/tree/develop/locale).
|
|
971
|
-
|
|
972
|
-
**Return:**
|
|
973
|
-
`string` Returns formatted date.
|
|
974
|
-
|
|
975
|
-
```js
|
|
976
|
-
{{!-- results in: 2021/10/24 --}}
|
|
977
|
-
{{formatDate 'YYYY/MM/DD' "2021-10-24T02:13:06.610Z"}}
|
|
978
|
-
|
|
979
|
-
{{!-- results in: 2021/10/24 --}}
|
|
980
|
-
{{formatDate 'YYYY/MM/DD' "2021-10-24T02:13:06.610Z" 'jp'}}
|
|
981
|
-
|
|
982
|
-
{{!-- results in: 2021/10/24 --}}
|
|
983
|
-
{{formatDate 'YYYY/MM/DD' "2021-10-24T02:13:06.610Z" 'es'}}
|
|
984
|
-
```
|
|
985
|
-
|
|
986
|
-
#### Number Helper
|
|
987
|
-
- `number2locale()`
|
|
988
|
-
Returns the language-sensitive representation of a number as a string.
|
|
989
|
-
|
|
990
|
-
**Parameters:**
|
|
991
|
-
- val: number|string
|
|
992
|
-
Target number or numeric string.
|
|
993
|
-
- locales: string|undefined
|
|
994
|
-
A string with a BCP 47 language tag, or an array of such strings.
|
|
995
|
-
Corresponds to the `locales` parameter of the Intl.NumberFormat() constructor.
|
|
996
|
-
In implementations without Intl.NumberFormat support, this parameter is ignored and the host's locale is usually used.
|
|
997
|
-
|
|
998
|
-
**Return:**
|
|
999
|
-
`string` A string with a language-sensitive representation of the given number.
|
|
1000
|
-
|
|
1001
|
-
```js
|
|
1002
|
-
{{!-- results in: 123,456.789 --}}
|
|
1003
|
-
{{number2locale 123456.789}}
|
|
1004
|
-
|
|
1005
|
-
{{!-- German uses comma as decimal separator and period for thousands. --}}
|
|
1006
|
-
{{!-- results in: 123.456,789 --}}
|
|
1007
|
-
{{number2locale 123456.789 'de-DE'}}
|
|
1008
|
-
```
|
|
1009
|
-
|
|
1010
|
-
#### Math Helper
|
|
1011
|
-
- `add()`
|
|
1012
|
-
Calculates the sum of two numbers.
|
|
1013
|
-
|
|
1014
|
-
**Parameters:**
|
|
1015
|
-
- val1: number|string
|
|
1016
|
-
The first number.
|
|
1017
|
-
- val2: number|string
|
|
1018
|
-
The second number.
|
|
1019
|
-
|
|
1020
|
-
**Return:**
|
|
1021
|
-
`number`
|
|
1022
|
-
|
|
1023
|
-
```js
|
|
1024
|
-
{{add 1 2}}
|
|
1025
|
-
```
|
|
1026
|
-
- `sub()`
|
|
1027
|
-
Calculates the difference of the given values.
|
|
1028
|
-
|
|
1029
|
-
**Parameters:**
|
|
1030
|
-
- val1: number|string
|
|
1031
|
-
The first number.
|
|
1032
|
-
- val2: number|string
|
|
1033
|
-
The second number.
|
|
1034
|
-
|
|
1035
|
-
**Return:**
|
|
1036
|
-
`number`
|
|
1037
|
-
|
|
1038
|
-
```js
|
|
1039
|
-
{{sub 5 2}}
|
|
1040
|
-
```
|
|
1041
|
-
- `multiply()`
|
|
1042
|
-
Calculate the multiplication of the given values.
|
|
1043
|
-
|
|
1044
|
-
**Parameters:**
|
|
1045
|
-
- val1: number|string
|
|
1046
|
-
The first number.
|
|
1047
|
-
- val2: number|string
|
|
1048
|
-
The second number.
|
|
1049
|
-
|
|
1050
|
-
**Return:**
|
|
1051
|
-
`number`
|
|
1052
|
-
|
|
1053
|
-
```js
|
|
1054
|
-
{{multiply 5 2}}
|
|
1055
|
-
```
|
|
1056
|
-
- `divide()`
|
|
1057
|
-
Compute the division of the given values.
|
|
1058
|
-
|
|
1059
|
-
**Parameters:**
|
|
1060
|
-
- val1: number|string
|
|
1061
|
-
The first number.
|
|
1062
|
-
- val2: number|string
|
|
1063
|
-
The second number.
|
|
1064
|
-
|
|
1065
|
-
**Return:**
|
|
1066
|
-
`number`
|
|
1067
|
-
|
|
1068
|
-
```js
|
|
1069
|
-
{{divide 10 2}}
|
|
1070
|
-
```
|
|
1071
|
-
- `ceil()`
|
|
1072
|
-
Round up the value.
|
|
1073
|
-
|
|
1074
|
-
**Parameters:**
|
|
1075
|
-
- val: number|string
|
|
1076
|
-
Number to be rounded to nearest greater integer.
|
|
1077
|
-
|
|
1078
|
-
**Return:**
|
|
1079
|
-
`number`
|
|
1080
|
-
|
|
1081
|
-
```js
|
|
1082
|
-
{{ceil 5.6}}
|
|
1083
|
-
```
|
|
1084
|
-
- `floor()`
|
|
1085
|
-
Rounds down a number.
|
|
1086
|
-
|
|
1087
|
-
**Parameters:**
|
|
1088
|
-
- val: number|string
|
|
1089
|
-
Number to be rounded to nearest lower integer.
|
|
1090
|
-
|
|
1091
|
-
**Return:**
|
|
1092
|
-
`number`
|
|
1093
|
-
|
|
1094
|
-
```js
|
|
1095
|
-
{{floor 5.6}}
|
|
1096
|
-
```
|
|
1097
|
-
- `abs()`
|
|
1098
|
-
Returns an absolute value.
|
|
1099
|
-
|
|
1100
|
-
**Parameters:**
|
|
1101
|
-
- val: number|string
|
|
1102
|
-
Number to perform absolute value operation on.
|
|
1103
|
-
|
|
1104
|
-
**Return:**
|
|
1105
|
-
`number`
|
|
1106
|
-
|
|
1107
|
-
```js
|
|
1108
|
-
{{abs -5.6}}
|
|
1109
|
-
```
|
|
1110
|
-
|
|
1111
|
-
### Model
|
|
1112
|
-
Models provide a way to interact with a specific table in your database.
|
|
1113
|
-
EXPRESS SWEET provides a [Sequelize](https://sequelize.org/docs/v6/) based model class that offers some great features, including.
|
|
1114
|
-
- Automatic database connection.
|
|
1115
|
-
- Basic CRUD methods.
|
|
1116
|
-
- And more.
|
|
1117
|
-
|
|
1118
|
-
This class provides a solid base from which to build your own models, allowing you to rapidly build out your application’s model layer.
|
|
1119
|
-
|
|
1120
|
-
#### Configuration
|
|
1121
|
-
The database configuration is defined in the `config/database.js` file.
|
|
1122
|
-
|
|
1123
|
-
Click [here](configuration_sample/esm/database.js) to download a sample ESM configuration
|
|
1124
|
-
and [here](configuration_sample/cjs/database.js) to download a sample CJS configuration.
|
|
1125
|
-
|
|
1126
|
-
- `username: string`
|
|
1127
|
-
The username which is used to authenticate against the database.
|
|
1128
|
-
- `password: string|null`
|
|
1129
|
-
The password which is used to authenticate against the database.
|
|
1130
|
-
The default is no password (`null`).
|
|
1131
|
-
- `database: string`
|
|
1132
|
-
The name of the database.
|
|
1133
|
-
- `host: string`
|
|
1134
|
-
The host of the relational database.
|
|
1135
|
-
- `port: number|null`
|
|
1136
|
-
The port of the relational database.
|
|
1137
|
-
The default is automatic selection (`null`).
|
|
1138
|
-
- `dialect: string`
|
|
1139
|
-
The dialect of the database you are connecting to.
|
|
1140
|
-
One of `mariadb`, `mysql`, `postgres`, `sqlite` and `mssql`.
|
|
1141
|
-
- `logging: boolean|(...message: any[]) => void`
|
|
1142
|
-
Set true to output the executed query etc. to the log.
|
|
1143
|
-
The default is no log output (`false`).
|
|
1144
|
-
- `timezone: string`
|
|
1145
|
-
Time zone dedicated to writing to the database.
|
|
1146
|
-
For example, for the Japanese time zone, do the following.
|
|
1147
|
-
```js
|
|
1148
|
-
timezone: '+09:00'
|
|
1149
|
-
```
|
|
1150
|
-
|
|
1151
|
-
#### Accessing Model
|
|
1152
|
-
Place the model in the `models/` directory of the root directory.
|
|
1153
|
-
When you load the model, you have immediate access to the model's functions for working with the database.
|
|
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:
|
|
1154
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**
|
|
507
|
+
|
|
508
|
+
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.
|
|
509
|
+
|
|
510
|
+
### Accessing Models
|
|
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.
|
|
513
|
+
|
|
514
|
+
**Basic model usage:**
|
|
1155
515
|
```js
|
|
1156
|
-
import BookModel from '../models/BookModel';
|
|
516
|
+
import BookModel from '../models/BookModel.js';
|
|
517
|
+
|
|
518
|
+
// Create a new record
|
|
519
|
+
// SQL: INSERT INTO book (title, userId) VALUES ('Beautiful', 1)
|
|
520
|
+
await BookModel.create({
|
|
521
|
+
title: 'Beautiful',
|
|
522
|
+
userId: 1
|
|
523
|
+
});
|
|
1157
524
|
|
|
1158
|
-
//
|
|
1159
|
-
|
|
525
|
+
// Find all records
|
|
526
|
+
// SQL: SELECT * FROM book
|
|
527
|
+
const allBooks = await BookModel.findAll();
|
|
1160
528
|
|
|
1161
|
-
//
|
|
1162
|
-
|
|
529
|
+
// Find with conditions
|
|
530
|
+
// SQL: SELECT * FROM book WHERE userId = 1
|
|
531
|
+
const userBooks = await BookModel.findAll({
|
|
532
|
+
where: { userId: 1 }
|
|
533
|
+
});
|
|
1163
534
|
|
|
1164
|
-
//
|
|
1165
|
-
|
|
535
|
+
// Update records
|
|
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
|
+
});
|
|
1166
547
|
|
|
1167
|
-
//
|
|
1168
|
-
|
|
548
|
+
// Find single record
|
|
549
|
+
// SQL: SELECT * FROM book WHERE title = 'Beautiful' LIMIT 1
|
|
550
|
+
const book = await BookModel.findOne({
|
|
551
|
+
where: { title: 'Beautiful' }
|
|
552
|
+
});
|
|
1169
553
|
```
|
|
1170
554
|
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
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:**
|
|
1175
560
|
```js
|
|
1176
561
|
import * as expx from 'express-sweet';
|
|
1177
562
|
|
|
1178
|
-
export default class extends expx.database.Model {
|
|
563
|
+
export default class UserModel extends expx.database.Model {
|
|
1179
564
|
static get table() {
|
|
1180
565
|
return 'user';
|
|
1181
566
|
}
|
|
@@ -1190,7 +575,6 @@ export default class extends expx.database.Model {
|
|
|
1190
575
|
name: this.DataTypes.STRING,
|
|
1191
576
|
email: this.DataTypes.STRING,
|
|
1192
577
|
password: this.DataTypes.STRING,
|
|
1193
|
-
icon: this.DataTypes.STRING,
|
|
1194
578
|
created: this.DataTypes.DATE,
|
|
1195
579
|
modified: this.DataTypes.DATE
|
|
1196
580
|
};
|
|
@@ -1198,1061 +582,579 @@ export default class extends expx.database.Model {
|
|
|
1198
582
|
}
|
|
1199
583
|
```
|
|
1200
584
|
|
|
1201
|
-
|
|
1202
|
-
This is the class that makes the database connection.
|
|
1203
|
-
See [here](https://sequelize.org/api/v6/class/src/sequelize.js~sequelize) for other available methods.
|
|
1204
|
-
|
|
1205
|
-
The database connection is automatic when the model is loaded.
|
|
1206
|
-
The configuration related to the database connection is defined in the `config/database.js` file.
|
|
1207
|
-
For more information on database configuration, see [Database configuration](#configuration-1).
|
|
1208
|
-
|
|
1209
|
-
##### Instance Methods
|
|
1210
|
-
- `public constructor()`
|
|
1211
|
-
Instantiate sequelize with name of database, username and password.
|
|
1212
|
-
- `public isConnect()`
|
|
1213
|
-
Test the connection by trying to authenticate. It runs `SELECT 1+1 AS result` query.
|
|
1214
|
-
|
|
1215
|
-
**Return:**
|
|
1216
|
-
`Promise<boolean>` Returns `true` if it can connect to the database, `false` if it cannot.
|
|
1217
|
-
|
|
1218
|
-
```js
|
|
1219
|
-
import * as expx from 'express-sweet';
|
|
1220
|
-
|
|
1221
|
-
// Create Database instance.
|
|
1222
|
-
const config = await expx.utils.loadDatabaseConfig();
|
|
1223
|
-
const database = new expx.database.Database(config.database, config.username, config.password, config);
|
|
1224
|
-
|
|
1225
|
-
// Check database connection.
|
|
1226
|
-
await database.isConnect();
|
|
1227
|
-
```
|
|
1228
|
-
- `public getConfig()`
|
|
1229
|
-
Returns the current database configuration object containing all sequelize options.
|
|
1230
|
-
|
|
1231
|
-
**Return:**
|
|
1232
|
-
`object` Database configuration object containing all sequelize options.
|
|
1233
|
-
|
|
1234
|
-
```js
|
|
1235
|
-
import * as expx from 'express-sweet';
|
|
1236
|
-
|
|
1237
|
-
// Create Database instance.
|
|
1238
|
-
const config = await expx.utils.loadDatabaseConfig();
|
|
1239
|
-
const database = new expx.database.Database(config.database, config.username, config.password, config);
|
|
1240
|
-
|
|
1241
|
-
// Get database configuration.
|
|
1242
|
-
const currentConfig = database.getConfig();
|
|
1243
|
-
console.log(currentConfig);
|
|
1244
|
-
```
|
|
1245
|
-
|
|
1246
|
-
#### Model Class extends [sequelize.Model](https://sequelize.org/api/v6/class/src/model.js~model)
|
|
1247
|
-
This is a class that abstracts the tables in the database.
|
|
1248
|
-
See [here](https://sequelize.org/api/v6/class/src/model.js~model) for more information on the methods and properties available in your model.
|
|
1249
|
-
|
|
1250
|
-
##### Class Properties
|
|
1251
|
-
- `protected static table: string`
|
|
1252
|
-
The name of the table that the model accesses. This member must be defined in a subclass.
|
|
1253
|
-
```js
|
|
1254
|
-
import * as expx from 'express-sweet';
|
|
1255
|
-
|
|
1256
|
-
export default class extends expx.database.Model {
|
|
1257
|
-
static get table() {
|
|
1258
|
-
return 'user';
|
|
1259
|
-
}
|
|
1260
|
-
}
|
|
1261
|
-
```
|
|
1262
|
-
- `protected static attributes: sequelize.ModelAttributes`
|
|
1263
|
-
List of columns in the table accessed by this model. This member must be defined in a subclass.
|
|
1264
|
-
```js
|
|
1265
|
-
import * as expx from 'express-sweet';
|
|
1266
|
-
|
|
1267
|
-
export default class extends expx.database.Model {
|
|
1268
|
-
static get attributes() {
|
|
1269
|
-
return {
|
|
1270
|
-
id: {
|
|
1271
|
-
type: this.DataTypes.INTEGER,
|
|
1272
|
-
primaryKey: true,
|
|
1273
|
-
autoIncrement: true
|
|
1274
|
-
},
|
|
1275
|
-
name: this.DataTypes.STRING,
|
|
1276
|
-
email: this.DataTypes.STRING,
|
|
1277
|
-
password: this.DataTypes.STRING,
|
|
1278
|
-
icon: this.DataTypes.STRING,
|
|
1279
|
-
created: this.DataTypes.DATE,
|
|
1280
|
-
modified: this.DataTypes.DATE
|
|
1281
|
-
};
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
```
|
|
1285
|
-
- `public static readonly DataTypes: {[key: string]: any}`
|
|
1286
|
-
A convenience class holding commonly used data types.
|
|
1287
|
-
This is an alias for `sequelize.DataTypes`.
|
|
1288
|
-
See [here](https://sequelize.org/api/v6/variable/index.html#static-variable-DataTypes) for details.
|
|
1289
|
-
```js
|
|
1290
|
-
{id: this.DataTypes.INTEGER}
|
|
1291
|
-
```
|
|
1292
|
-
- `public static readonly Op: {[key: string]: any}`
|
|
1293
|
-
Operator symbols to be used when querying data.
|
|
1294
|
-
This is an alias for `sequelize.Op`.
|
|
1295
|
-
See [here](https://sequelize.org/docs/v6/core-concepts/model-querying-basics/#operators) for details.
|
|
1296
|
-
```js
|
|
1297
|
-
import BookModel from '../models/BookModel';
|
|
1298
|
-
|
|
1299
|
-
// SELECT * FROM book WHERE title = 'Beautiful' AND genre = 'Nonfiction';
|
|
1300
|
-
BookModel.findOne({
|
|
1301
|
-
where: {
|
|
1302
|
-
[BookModel.Op.and]: [
|
|
1303
|
-
{title: 'Beautiful'},
|
|
1304
|
-
{genre: 'Nonfiction'}
|
|
1305
|
-
]
|
|
1306
|
-
}
|
|
1307
|
-
});
|
|
585
|
+
### Model Relationships
|
|
1308
586
|
|
|
1309
|
-
|
|
1310
|
-
BookModel.findAll({
|
|
1311
|
-
where: {
|
|
1312
|
-
[BookModel.Op.or]: [
|
|
1313
|
-
{title: 'Beautiful'},
|
|
1314
|
-
{title: 'Lose Yourself'}
|
|
1315
|
-
]
|
|
1316
|
-
}
|
|
1317
|
-
});
|
|
587
|
+
EXPRESS SWEET supports Sequelize associations for building data relationships:
|
|
1318
588
|
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
589
|
+
```js
|
|
590
|
+
// Define associations in your model
|
|
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:
|
|
762
|
+
|
|
763
|
+
```handlebars
|
|
764
|
+
{{!-- Localized number formatting --}}
|
|
765
|
+
<p>Price: ${{number2locale price 'en-US'}}</p>
|
|
766
|
+
<p>Total: €{{number2locale total 'de-DE'}}</p>
|
|
767
|
+
<p>Count: {{number2locale userCount 'ja-JP'}}</p>
|
|
768
|
+
```
|
|
769
|
+
|
|
770
|
+
#### Math Helpers
|
|
771
|
+
|
|
772
|
+
Mathematical operations for template calculations:
|
|
773
|
+
|
|
774
|
+
```handlebars
|
|
775
|
+
{{!-- Basic arithmetic --}}
|
|
776
|
+
<p>Total: ${{add price tax}}</p>
|
|
777
|
+
<p>Discount: ${{subtract price discount}}</p>
|
|
778
|
+
<p>Amount: ${{multiply quantity unitPrice}}</p>
|
|
779
|
+
<p>Average: {{divide total count}}</p>
|
|
780
|
+
|
|
781
|
+
{{!-- Rounding functions --}}
|
|
782
|
+
<p>Rounded up: {{ceil 4.3}}</p> {{!-- Results: 5 --}}
|
|
783
|
+
<p>Rounded down: {{floor 4.7}}</p> {{!-- Results: 4 --}}
|
|
784
|
+
<p>Absolute value: {{abs -15}}</p> {{!-- Results: 15 --}}
|
|
785
|
+
```
|
|
786
|
+
|
|
787
|
+
For complete documentation of all helpers and their options, see the [Handlebars Helpers API Reference](https://takuya-motoshima.github.io/express-sweet/modules/handlebars_helpers.html).
|
|
788
|
+
|
|
789
|
+
## Authentication
|
|
790
|
+
|
|
791
|
+
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.
|
|
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.
|
|
794
|
+
|
|
795
|
+
### Login Example
|
|
796
|
+
|
|
797
|
+
#### Asynchronous Login (Ajax)
|
|
798
|
+
|
|
799
|
+
Returns the authentication result for frontend processing:
|
|
800
|
+
|
|
801
|
+
```js
|
|
802
|
+
import {Router} from 'express';
|
|
803
|
+
import * as expx from 'express-sweet';
|
|
804
|
+
|
|
805
|
+
const router = Router();
|
|
806
|
+
router.post('/login', async (req, res, next) => {
|
|
807
|
+
const isAuthenticated = await expx.services.Authentication.authenticate(req, res, next);
|
|
808
|
+
res.json(isAuthenticated);
|
|
809
|
+
});
|
|
810
|
+
|
|
811
|
+
export default router;
|
|
812
|
+
```
|
|
813
|
+
|
|
814
|
+
**Frontend HTML example:**
|
|
815
|
+
```html
|
|
816
|
+
<form id="loginForm">
|
|
817
|
+
<label>Email</label>
|
|
818
|
+
<input type="email" name="email" required autofocus>
|
|
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>
|
|
843
|
+
```
|
|
844
|
+
|
|
845
|
+
#### Synchronous Login (Form Submit)
|
|
846
|
+
|
|
847
|
+
Redirects based on authentication result:
|
|
848
|
+
|
|
849
|
+
```js
|
|
850
|
+
import {Router} from 'express';
|
|
851
|
+
import * as expx from 'express-sweet';
|
|
852
|
+
|
|
853
|
+
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
|
+
|
|
882
|
+
```js
|
|
883
|
+
import {Router} from 'express';
|
|
884
|
+
import * as expx from 'express-sweet';
|
|
885
|
+
|
|
886
|
+
const router = Router();
|
|
887
|
+
router.get('/logout', (req, res) => {
|
|
888
|
+
expx.services.Authentication.logout(req);
|
|
889
|
+
res.redirect('/login');
|
|
890
|
+
});
|
|
891
|
+
|
|
892
|
+
export default router;
|
|
893
|
+
```
|
|
894
|
+
|
|
895
|
+
**Frontend HTML example:**
|
|
896
|
+
```html
|
|
897
|
+
<a href="/api/users/logout">Logout</a>
|
|
898
|
+
```
|
|
899
|
+
|
|
900
|
+
For detailed authentication configuration options, see the [Configuration](#configuration) section and [Authentication API Reference](https://takuya-motoshima.github.io/express-sweet/classes/services.Authentication.html).
|
|
901
|
+
|
|
902
|
+
## Examples
|
|
903
|
+
|
|
904
|
+
### RESTful API Development
|
|
905
|
+
|
|
906
|
+
Build RESTful APIs with essential CRUD operations:
|
|
907
|
+
|
|
908
|
+
```js
|
|
909
|
+
import {Router} from 'express';
|
|
910
|
+
import BookModel from '../models/BookModel.js';
|
|
911
|
+
|
|
912
|
+
const router = Router();
|
|
913
|
+
|
|
914
|
+
// GET /api/books - List all books
|
|
915
|
+
router.get('/books', async (req, res, next) => {
|
|
916
|
+
try {
|
|
1372
917
|
const books = await BookModel.findAll({
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
BookModel.fn('CHAR_LENGTH', BookModel.col('title')),
|
|
1376
|
-
{[BookModel.Op.lte]: 10}
|
|
1377
|
-
),
|
|
1378
|
-
raw: true
|
|
918
|
+
order: [['created', 'DESC']],
|
|
919
|
+
include: ['UserModel']
|
|
1379
920
|
});
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
BookModel.
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
##### Class Methods
|
|
1396
|
-
- `public static association()`
|
|
1397
|
-
Associate the model.
|
|
1398
|
-
Define associations with other models such as `hasOne`, `hasMany`, `belongsTo`, `belongsToMany`.
|
|
1399
|
-
This method is called automatically from within the `mount` method, so you don't have to run it yourself.
|
|
1400
|
-
See the [here](https://sequelize.org/api/v6/class/src/associations/base.js~association) for more information.
|
|
1401
|
-
If you omit the alias (`as`) option, the associated name will be hasOne, singular for belongsTo, and plural for hasMany.
|
|
1402
|
-
```js
|
|
1403
|
-
import * as expx from 'express-sweet';
|
|
1404
|
-
import ProfileModel from './ProfileModel';
|
|
1405
|
-
|
|
1406
|
-
export default class extends expx.database.Model {
|
|
1407
|
-
static association() {
|
|
1408
|
-
// User has one profile.
|
|
1409
|
-
this.hasOne(ProfileModel, {
|
|
1410
|
-
foreignKey: 'userId', // profile.userId
|
|
1411
|
-
sourceKey: 'id', // user.id
|
|
1412
|
-
as: 'profile'
|
|
1413
|
-
});
|
|
1414
|
-
}
|
|
1415
|
-
}
|
|
1416
|
-
```
|
|
1417
|
-
- `public static begin()`
|
|
1418
|
-
Starts a transaction and returns a transaction object to identify the running transaction.
|
|
1419
|
-
This is an alias for the `sequelize.Sequelize.transaction()` method.
|
|
1420
|
-
See [here](https://sequelize.org/api/v6/class/src/sequelize.js~sequelize#instance-method-transaction) for details.
|
|
1421
|
-
|
|
1422
|
-
**Parameters:**
|
|
1423
|
-
- options?: sequelize.TransactionOptions
|
|
1424
|
-
Options provided when the transaction is created.
|
|
1425
|
-
|
|
1426
|
-
**Return:**
|
|
1427
|
-
`Promise<sequelize.Transaction>` Returns a transaction object to identify the transaction being executed.
|
|
1428
|
-
|
|
1429
|
-
Simple transaction usage example.
|
|
1430
|
-
```js
|
|
1431
|
-
import BookModel from '../models/BookModel';
|
|
1432
|
-
|
|
1433
|
-
let transaction;
|
|
1434
|
-
try {
|
|
1435
|
-
transaction = await BookModel.begin();
|
|
1436
|
-
const book = await BookModel.create({title: 'Beautiful'}, {transaction});
|
|
1437
|
-
await transaction.commit();
|
|
1438
|
-
} catch {
|
|
1439
|
-
if (transaction)
|
|
1440
|
-
await transaction.rollback();
|
|
1441
|
-
}
|
|
1442
|
-
```
|
|
1443
|
-
|
|
1444
|
-
You can also use transaction options.
|
|
1445
|
-
```js
|
|
1446
|
-
import BookModel from '../models/BookModel';
|
|
1447
|
-
|
|
1448
|
-
let transaction;
|
|
1449
|
-
try {
|
|
1450
|
-
transaction = await BookModel.begin({
|
|
1451
|
-
isolationLevel: BookModel.Transaction.ISOLATION_LEVELS.REPEATABLE_READ,
|
|
1452
|
-
type: BookModel.Transaction.TYPES.DEFERRED,
|
|
1453
|
-
});
|
|
1454
|
-
const book = await BookModel.findOne({where: {id: 1}}, {transaction});
|
|
1455
|
-
book.title = 'Beautiful';
|
|
1456
|
-
await book.save({transaction});
|
|
1457
|
-
await transaction.commit();
|
|
1458
|
-
|
|
1459
|
-
// Load updated data.
|
|
1460
|
-
await book.reload();
|
|
1461
|
-
} catch {
|
|
1462
|
-
if (transaction)
|
|
1463
|
-
await transaction.rollback();
|
|
1464
|
-
}
|
|
1465
|
-
```
|
|
1466
|
-
- `public static create()`
|
|
1467
|
-
Builds a new model instance and calls `save` on it.
|
|
1468
|
-
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-create) for details.
|
|
1469
|
-
|
|
1470
|
-
**Parameters:**
|
|
1471
|
-
- values: object
|
|
1472
|
-
Hash of data values to create new record with.
|
|
1473
|
-
- options: object
|
|
1474
|
-
Build and query options.
|
|
1475
|
-
|
|
1476
|
-
**Return:**
|
|
1477
|
-
`Promise<Model>` Returns a model that contains the data for the added record.
|
|
1478
|
-
|
|
1479
|
-
```js
|
|
1480
|
-
import BookModel from '../models/BookModel';
|
|
1481
|
-
|
|
1482
|
-
// INSERT INTO `book` (`id`,`title`) VALUES (DEFAULT,'Beautiful');
|
|
1483
|
-
await BookModel.create({title: 'Beautiful'});
|
|
1484
|
-
```
|
|
1485
|
-
- `public static save()`
|
|
1486
|
-
Validates this instance, and if the validation passes, persists it to the database.
|
|
1487
|
-
See [here](https://sequelize.org/api/v6/class/src/model.js~model#instance-method-save) for details.
|
|
1488
|
-
|
|
1489
|
-
**Parameters:**
|
|
1490
|
-
- options: object
|
|
1491
|
-
save options.
|
|
1492
|
-
|
|
1493
|
-
**Return:**
|
|
1494
|
-
`Promise<Model>` Returns a model that contains data for manipulated records such as add and update.
|
|
1495
|
-
|
|
1496
|
-
```js
|
|
1497
|
-
import BookModel from '../models/BookModel';
|
|
1498
|
-
|
|
1499
|
-
// INSERT INTO `book` (`id`,`title`) VALUES (DEFAULT,'Beautiful');
|
|
1500
|
-
const book = BookModel.build({title: 'Beautiful'});
|
|
1501
|
-
await book.save();
|
|
1502
|
-
|
|
1503
|
-
// UPDATE `book` SET `title`='Lose Yourself' WHERE `id` = 1;
|
|
1504
|
-
book.title = 'Lose Yourself';
|
|
1505
|
-
await book.save();
|
|
1506
|
-
```
|
|
1507
|
-
- `public static findOne()`
|
|
1508
|
-
Search for a single instance.
|
|
1509
|
-
Returns the first instance found, or null if none can be found.
|
|
1510
|
-
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-findOne) for details.
|
|
1511
|
-
|
|
1512
|
-
**Parameters:**
|
|
1513
|
-
- options: object
|
|
1514
|
-
A hash of options to describe the scope of the search.
|
|
1515
|
-
|
|
1516
|
-
**Return:**
|
|
1517
|
-
`Promise<Model|null>` Returns a Model containing the first data found in the database.
|
|
1518
|
-
|
|
1519
|
-
```js
|
|
1520
|
-
import BookModel from '../models/BookModel';
|
|
1521
|
-
|
|
1522
|
-
// SELECT `id`, `title`, `created`, `modified` FROM `book` AS `book` LIMIT 1;
|
|
1523
|
-
await BookModel.findOne();
|
|
1524
|
-
```
|
|
1525
|
-
- `public static findAll()`
|
|
1526
|
-
Search for multiple instances.
|
|
1527
|
-
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-findAll) for details.
|
|
1528
|
-
|
|
1529
|
-
**Parameters:**
|
|
1530
|
-
- options: object
|
|
1531
|
-
A hash of options to describe the scope of the search.
|
|
1532
|
-
|
|
1533
|
-
**Return:**
|
|
1534
|
-
`Promise<Array<Model>>` Returns a model containing the data found in the database.
|
|
1535
|
-
|
|
1536
|
-
```js
|
|
1537
|
-
import BookModel from '../models/BookModel';
|
|
1538
|
-
|
|
1539
|
-
// SELECT `id`, `title`, `created`, `modified` FROM `book` AS `book` WHERE `book`.`title` LIKE 'Beautiful%';
|
|
1540
|
-
await BookModel.findAll({
|
|
1541
|
-
where: {
|
|
1542
|
-
title: {
|
|
1543
|
-
[BookModel.Op.like]: 'Beautiful%'
|
|
1544
|
-
}
|
|
1545
|
-
}
|
|
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
|
|
1546
936
|
});
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
**Parameters:**
|
|
1553
|
-
- options: object
|
|
1554
|
-
A hash of options to describe the scope of the search.
|
|
1555
|
-
|
|
1556
|
-
**Return:**
|
|
1557
|
-
`Promise<number>` Returns the count of records that match the condition.
|
|
1558
|
-
|
|
1559
|
-
```js
|
|
1560
|
-
import BookModel from '../models/BookModel';
|
|
1561
|
-
|
|
1562
|
-
// SELECT count(*) AS `count` FROM `book` AS `book`;
|
|
1563
|
-
await BookModel.count();
|
|
1564
|
-
```
|
|
1565
|
-
- `public static update()`
|
|
1566
|
-
Update multiple instances that match the where options.
|
|
1567
|
-
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-update) for details.
|
|
1568
|
-
|
|
1569
|
-
**Parameters:**
|
|
1570
|
-
- values: object
|
|
1571
|
-
hash of values to update.
|
|
1572
|
-
- options: object
|
|
1573
|
-
update options.
|
|
1574
|
-
|
|
1575
|
-
**Return:**
|
|
1576
|
-
`Promise<Array<number, number>>` The first element is always the number of affected rows, while the second element is the actual affected rows (only supported in postgres with `options.returning` true).
|
|
1577
|
-
|
|
1578
|
-
```js
|
|
1579
|
-
import BookModel from '../models/BookModel';
|
|
1580
|
-
|
|
1581
|
-
// UPDATE `book` SET `title`='Lose Yourself' WHERE `id` = 1;
|
|
1582
|
-
await BookModel.update({title: 'Lose Yourself'}, {where: {id: 1}});
|
|
1583
|
-
```
|
|
1584
|
-
- `public static upsert()`
|
|
1585
|
-
Insert or update a single row.
|
|
1586
|
-
An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found.
|
|
1587
|
-
Note that the unique index must be defined in your sequelize model and not just in the table.
|
|
1588
|
-
Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.
|
|
1589
|
-
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-upsert) for details.
|
|
1590
|
-
|
|
1591
|
-
**Parameters:**
|
|
1592
|
-
- values: object
|
|
1593
|
-
hash of values to upsert.
|
|
1594
|
-
- options: object
|
|
1595
|
-
upsert options.
|
|
1596
|
-
|
|
1597
|
-
**Return:**
|
|
1598
|
-
`Promise<Model, boolean|null>` returns record and whether row was created or updated as boolean. For Postgres/SQLite dialects boolean value is always null.
|
|
1599
|
-
|
|
1600
|
-
```js
|
|
1601
|
-
import BookModel from '../models/BookModel';
|
|
1602
|
-
|
|
1603
|
-
// INSERT INTO `book` (`title`) VALUES (?) ON DUPLICATE KEY UPDATE `title`=VALUES(`title`);
|
|
1604
|
-
await BookModel.upsert({title: 'Lose Yourself'});
|
|
1605
|
-
```
|
|
1606
|
-
- `public static destroy()`
|
|
1607
|
-
Delete multiple instances, or set their deletedAt timestamp to the current time if paranoid is enabled.
|
|
1608
|
-
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-destroy) for details.
|
|
1609
|
-
|
|
1610
|
-
**Parameters:**
|
|
1611
|
-
- options: object
|
|
1612
|
-
destroy options.
|
|
1613
|
-
|
|
1614
|
-
**Return:**
|
|
1615
|
-
`Promise<number>` The number of destroyed rows.
|
|
1616
|
-
|
|
1617
|
-
```js
|
|
1618
|
-
import BookModel from '../models/BookModel';
|
|
1619
|
-
|
|
1620
|
-
// DELETE FROM `user` WHERE `id` = 1;
|
|
1621
|
-
await BookModel.destroy({where: {id :1}});
|
|
1622
|
-
```
|
|
1623
|
-
- `public static hasOne()`
|
|
1624
|
-
Creates an association between this (the source) and the provided target.
|
|
1625
|
-
The foreign key is added on the target.
|
|
1626
|
-
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-hasOne) for details.
|
|
1627
|
-
|
|
1628
|
-
**Parameters:**
|
|
1629
|
-
- target: Model
|
|
1630
|
-
The target model.
|
|
1631
|
-
- options: object
|
|
1632
|
-
hasOne association options.
|
|
1633
|
-
|
|
1634
|
-
**Return:**
|
|
1635
|
-
[`sequelize.HasOne`](https://sequelize.org/api/v6/class/src/associations/has-one.js~hasone) One-to-one association.
|
|
1636
|
-
|
|
1637
|
-
For one-to-one association we will use two tables as an example they are User and Profile table.
|
|
1638
|
-
User table has one Profile table and Profile table belongs to the User table.
|
|
1639
|
-
Here's the relation diagram for it.
|
|
1640
|
-
|
|
1641
|
-

|
|
1642
|
-
|
|
1643
|
-
HasOne put the association key in the target model.
|
|
1644
|
-
Here User can exist without a Profile, but the vice versa is not possible.
|
|
1645
|
-
This means, we will insert userId field to Profile model’s table.
|
|
1646
|
-
|
|
1647
|
-
This is a user model that defines an association in which the user has one profile.
|
|
1648
|
-
```js
|
|
1649
|
-
import * as expx from 'express-sweet';
|
|
1650
|
-
import ProfileModel from './ProfileModel';
|
|
1651
|
-
|
|
1652
|
-
export default class extends expx.database.Model {
|
|
1653
|
-
static association() {
|
|
1654
|
-
// User has one profile.
|
|
1655
|
-
this.hasOne(ProfileModel, {
|
|
1656
|
-
foreignKey: 'userId', // profile.userId
|
|
1657
|
-
sourceKey: 'id', // user.id
|
|
1658
|
-
as: 'profile'
|
|
1659
|
-
});
|
|
1660
|
-
}
|
|
1661
|
-
}
|
|
1662
|
-
```
|
|
1663
|
-
|
|
1664
|
-
This is an example of record search.
|
|
1665
|
-
```js
|
|
1666
|
-
import UserModel from '../models/UserModel';
|
|
1667
|
-
|
|
1668
|
-
// SELECT
|
|
1669
|
-
// `user`.`id`,
|
|
1670
|
-
// `user`.`name`,
|
|
1671
|
-
// `profile`.`id` AS `profile.id`,
|
|
1672
|
-
// `profile`.`userId` AS `profile.userId`,
|
|
1673
|
-
// `profile`.`address` AS `profile.address`,
|
|
1674
|
-
// `profile`.`tel` AS `profile.tel`
|
|
1675
|
-
// FROM
|
|
1676
|
-
// `user` AS `user`
|
|
1677
|
-
// LEFT OUTER JOIN `profile` AS `profile` ON `user`.`id` = `profile`.`userId`;
|
|
1678
|
-
//
|
|
1679
|
-
// results in: [
|
|
1680
|
-
// {
|
|
1681
|
-
// "id": 1,
|
|
1682
|
-
// "name": "Robin",
|
|
1683
|
-
// "profile": {
|
|
1684
|
-
// "userId": 1,
|
|
1685
|
-
// "address": "777 Brockton Avenue, Abington MA 2351",
|
|
1686
|
-
// "tel": "202-555-0105"
|
|
1687
|
-
// }
|
|
1688
|
-
// }
|
|
1689
|
-
// ]
|
|
1690
|
-
await UserModel.findAll({
|
|
1691
|
-
attributes: ['id', 'name'],
|
|
1692
|
-
include: [
|
|
1693
|
-
{
|
|
1694
|
-
association: 'profile',
|
|
1695
|
-
attributes: ['userId', 'address', 'tel']
|
|
1696
|
-
},
|
|
1697
|
-
]
|
|
937
|
+
|
|
938
|
+
res.status(201).json({
|
|
939
|
+
success: true,
|
|
940
|
+
book: newBook
|
|
1698
941
|
});
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
BelongsTo put the associations key in the source model.
|
|
1722
|
-
Here User can exist without a Profile, but the vice versa is not possible.
|
|
1723
|
-
This means, we will insert userId field to Profile model’s table.
|
|
1724
|
-
|
|
1725
|
-
This is a profile model that defines an association whose profile belongs to one user.
|
|
1726
|
-
```js
|
|
1727
|
-
import * as expx from 'express-sweet';
|
|
1728
|
-
import UserModel from './UserModel';
|
|
1729
|
-
|
|
1730
|
-
export default class extends expx.database.Model {
|
|
1731
|
-
static association() {
|
|
1732
|
-
// Profile belongs to one user.
|
|
1733
|
-
this.belongsTo(UserModel, {
|
|
1734
|
-
foreignKey: 'userId', // profile.userId,
|
|
1735
|
-
targetKey: 'id', // user.id
|
|
1736
|
-
as: 'user'
|
|
1737
|
-
});
|
|
1738
|
-
}
|
|
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
|
+
});
|
|
1739
963
|
}
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
// SELECT
|
|
1747
|
-
// `profile`.`id`,
|
|
1748
|
-
// `profile`.`userId`,
|
|
1749
|
-
// `profile`.`address`,
|
|
1750
|
-
// `profile`.`tel`,
|
|
1751
|
-
// `user`.`id` AS `user.id`,
|
|
1752
|
-
// `user`.`name` AS `user.name`
|
|
1753
|
-
// FROM
|
|
1754
|
-
// `profile` AS `profile`
|
|
1755
|
-
// INNER JOIN `user` AS `user` ON `profile`.`userId` = `user`.`id`;
|
|
1756
|
-
//
|
|
1757
|
-
// results in: [
|
|
1758
|
-
// {
|
|
1759
|
-
// "userId": 1,
|
|
1760
|
-
// "address": "777 Brockton Avenue, Abington MA 2351",
|
|
1761
|
-
// "tel": "202-555-0105",
|
|
1762
|
-
// "user": {
|
|
1763
|
-
// "id": 1,
|
|
1764
|
-
// "name": "Robin"
|
|
1765
|
-
// }
|
|
1766
|
-
// }
|
|
1767
|
-
// ]
|
|
1768
|
-
await ProfileModel.findAll({
|
|
1769
|
-
attributes: ['userId', 'address', 'tel'],
|
|
1770
|
-
include: {
|
|
1771
|
-
association: 'user',
|
|
1772
|
-
required: true,
|
|
1773
|
-
attributes: ['id', 'name']
|
|
1774
|
-
}
|
|
964
|
+
|
|
965
|
+
const updatedBook = await BookModel.findByPk(bookId);
|
|
966
|
+
res.json({
|
|
967
|
+
success: true,
|
|
968
|
+
book: updatedBook
|
|
1775
969
|
});
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
This is a user model that defines an association in which the user has many comments.
|
|
1803
|
-
```js
|
|
1804
|
-
import * as expx from 'express-sweet';
|
|
1805
|
-
import CommentModel from './CommentModel';
|
|
1806
|
-
|
|
1807
|
-
export default class extends expx.database.Model {
|
|
1808
|
-
static association() {
|
|
1809
|
-
// User has many comments.
|
|
1810
|
-
this.hasMany(CommentModel, {
|
|
1811
|
-
foreignKey: 'userId', // comment.userId
|
|
1812
|
-
sourceKey: 'id', // user.id
|
|
1813
|
-
as: 'comments'
|
|
1814
|
-
});
|
|
1815
|
-
}
|
|
1816
|
-
}
|
|
1817
|
-
```
|
|
1818
|
-
|
|
1819
|
-
This is an example of record search.
|
|
1820
|
-
```js
|
|
1821
|
-
import UserModel from '../models/UserModel';
|
|
1822
|
-
|
|
1823
|
-
// SELECT
|
|
1824
|
-
// `user`.`id`,
|
|
1825
|
-
// `user`.`name`,
|
|
1826
|
-
// `comments`.`id` AS `comments.id`,
|
|
1827
|
-
// `comments`.`userId` AS `comments.userId`,
|
|
1828
|
-
// `comments`.`text` AS `comments.text`
|
|
1829
|
-
// FROM
|
|
1830
|
-
// `user` AS `user`
|
|
1831
|
-
// LEFT OUTER JOIN `comment` AS `comments` ON `user`.`id` = `comments`.`userId`;
|
|
1832
|
-
//
|
|
1833
|
-
// results in: [
|
|
1834
|
-
// {
|
|
1835
|
-
// "id": 1,
|
|
1836
|
-
// "name": "Robin",
|
|
1837
|
-
// "comments": [
|
|
1838
|
-
// {
|
|
1839
|
-
// "userId": 1,
|
|
1840
|
-
// "text": "From Robin #1"
|
|
1841
|
-
// },
|
|
1842
|
-
// {
|
|
1843
|
-
// "userId": 1,
|
|
1844
|
-
// "text": "From Robin #2"
|
|
1845
|
-
// }
|
|
1846
|
-
// ]
|
|
1847
|
-
// }
|
|
1848
|
-
// ]
|
|
1849
|
-
await UserModel.findAll({
|
|
1850
|
-
attributes: ['id', 'name'],
|
|
1851
|
-
include: {
|
|
1852
|
-
association: 'comments',
|
|
1853
|
-
attributes: ['userId', 'text']
|
|
1854
|
-
}
|
|
970
|
+
} catch (error) {
|
|
971
|
+
next(error);
|
|
972
|
+
}
|
|
973
|
+
});
|
|
974
|
+
|
|
975
|
+
export default router;
|
|
976
|
+
```
|
|
977
|
+
|
|
978
|
+
### Advanced View Usage
|
|
979
|
+
|
|
980
|
+
Comprehensive view rendering with layouts and data:
|
|
981
|
+
|
|
982
|
+
```js
|
|
983
|
+
import {Router} from 'express';
|
|
984
|
+
import UserModel from '../models/UserModel.js';
|
|
985
|
+
import BookModel from '../models/BookModel.js';
|
|
986
|
+
|
|
987
|
+
const router = Router();
|
|
988
|
+
|
|
989
|
+
// Render page with custom layout
|
|
990
|
+
router.get('/profile/:id', async (req, res) => {
|
|
991
|
+
try {
|
|
992
|
+
const user = await UserModel.findOne({
|
|
993
|
+
where: { id: req.params.id },
|
|
994
|
+
include: ['ProfileModel']
|
|
1855
995
|
});
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
If you want to retrieve child rows as an array within the parent row, you should **disable the `raw` option**.
|
|
1863
|
-
|
|
1864
|
-
Enabling the `raw` option will result in the parent row being duplicated for each child row. This behavior is also discussed in this [GitHub issue](https://github.com/sequelize/sequelize/issues/11988).
|
|
1865
|
-
|
|
1866
|
-
**Example:**
|
|
1867
|
-
|
|
1868
|
-
**With `raw: true`:**
|
|
1869
|
-
|
|
1870
|
-
```json
|
|
1871
|
-
[
|
|
1872
|
-
{
|
|
1873
|
-
"id": 1,
|
|
1874
|
-
"name": "Robin",
|
|
1875
|
-
{
|
|
1876
|
-
"userId": 1,
|
|
1877
|
-
"text": "From Robin #1"
|
|
1878
|
-
}
|
|
1879
|
-
},
|
|
1880
|
-
{
|
|
1881
|
-
"id": 1,
|
|
1882
|
-
"name": "Robin",
|
|
1883
|
-
{
|
|
1884
|
-
"userId": 1,
|
|
1885
|
-
"text": "From Robin #2"
|
|
1886
|
-
}
|
|
1887
|
-
}
|
|
1888
|
-
]
|
|
1889
|
-
```
|
|
1890
|
-
|
|
1891
|
-
**With `raw: false` (default):**
|
|
1892
|
-
|
|
1893
|
-
```json
|
|
1894
|
-
[
|
|
1895
|
-
{
|
|
1896
|
-
"id": 1,
|
|
1897
|
-
"name": "Robin",
|
|
1898
|
-
"comments": [
|
|
1899
|
-
{
|
|
1900
|
-
"userId": 1,
|
|
1901
|
-
"text": "From Robin #1"
|
|
1902
|
-
},
|
|
1903
|
-
{
|
|
1904
|
-
"userId": 1,
|
|
1905
|
-
"text": "From Robin #2"
|
|
1906
|
-
}
|
|
1907
|
-
]
|
|
1908
|
-
}
|
|
1909
|
-
]
|
|
1910
|
-
```
|
|
1911
|
-
|
|
1912
|
-
- `public static belongsToMany()`
|
|
1913
|
-
Create an N:M association with a join table.
|
|
1914
|
-
Defining through is required.
|
|
1915
|
-
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-belongsToMany) for details.
|
|
1916
|
-
|
|
1917
|
-
**Parameters:**
|
|
1918
|
-
- target: Model
|
|
1919
|
-
The target model.
|
|
1920
|
-
- options: object
|
|
1921
|
-
belongsToMany association options.
|
|
1922
|
-
|
|
1923
|
-
**Return:**
|
|
1924
|
-
[`sequelize.BelongsToMany`](https://sequelize.org/api/v6/class/src/associations/belongs-to-many.js~belongstomany) Many-to-many association with a join table.
|
|
1925
|
-
|
|
1926
|
-
For many-to-many association we will use two tables as an example they are User and Book table.
|
|
1927
|
-
User is marking down Books that he has read. Each user can mark as many books as they want, creating a many to many association between User and Books.
|
|
1928
|
-
Books can belong to many users.
|
|
1929
|
-
Here's the relation diagram for it.
|
|
1930
|
-
|
|
1931
|
-

|
|
1932
|
-
|
|
1933
|
-
The BlongsToMany put the association key in the target model.
|
|
1934
|
-
Here user and book share a many to many relationship.
|
|
1935
|
-
Each user can make multiple books, and each book can be associated with multiple users.
|
|
1936
|
-
|
|
1937
|
-
This is a user model that defines an association where users and books have a many-to-many relationship.
|
|
1938
|
-
```js
|
|
1939
|
-
import * as expx from 'express-sweet';
|
|
1940
|
-
import BookModel from './BookModel';
|
|
1941
|
-
|
|
1942
|
-
export default class extends expx.database.Model {
|
|
1943
|
-
static association() {
|
|
1944
|
-
// Users have many books, and books belong to many users.
|
|
1945
|
-
this.belongsToMany(BookModel, {
|
|
1946
|
-
foreignKey: 'userId', // book.userId
|
|
1947
|
-
sourceKey: 'id', // user.id
|
|
1948
|
-
as: 'books'
|
|
1949
|
-
});
|
|
1950
|
-
}
|
|
996
|
+
|
|
997
|
+
if (!user) {
|
|
998
|
+
return res.status(404).render('errors/404', {
|
|
999
|
+
title: 'User Not Found'
|
|
1000
|
+
});
|
|
1951
1001
|
}
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
// SELECT
|
|
1959
|
-
// `user`.`id`,
|
|
1960
|
-
// `user`.`name`,
|
|
1961
|
-
// `books`.`id` AS `books.id`,
|
|
1962
|
-
// `books`.`userId` AS `books.userId`,
|
|
1963
|
-
// `books`.`title` AS `books.title`
|
|
1964
|
-
// FROM
|
|
1965
|
-
// `user` AS `user`
|
|
1966
|
-
// LEFT OUTER JOIN `book` AS `books` ON `user`.`id` = `books`.`userId`;
|
|
1967
|
-
//
|
|
1968
|
-
// results in: [
|
|
1969
|
-
// {
|
|
1970
|
-
// "id": 1,
|
|
1971
|
-
// "name": "Robin",
|
|
1972
|
-
// "books": [
|
|
1973
|
-
// {
|
|
1974
|
-
// "userId": 1,
|
|
1975
|
-
// "title": "Beautiful"
|
|
1976
|
-
// },
|
|
1977
|
-
// {
|
|
1978
|
-
// "userId": 1,
|
|
1979
|
-
// "title": "Lose Yourself"
|
|
1980
|
-
// }
|
|
1981
|
-
// ]
|
|
1982
|
-
// }
|
|
1983
|
-
// ]
|
|
1984
|
-
await UserModel.findAll({
|
|
1985
|
-
attributes: ['id', 'name'],
|
|
1986
|
-
include: {
|
|
1987
|
-
association: 'books',
|
|
1988
|
-
attributes: ['userId', 'title']
|
|
1989
|
-
}
|
|
1002
|
+
|
|
1003
|
+
const userBooks = await BookModel.findAll({
|
|
1004
|
+
where: { userId: req.params.id },
|
|
1005
|
+
order: [['created', 'DESC']],
|
|
1006
|
+
limit: 10
|
|
1990
1007
|
});
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
**Parameters:**
|
|
1999
|
-
- sql: string
|
|
2000
|
-
SQL string.
|
|
2001
|
-
- options: object
|
|
2002
|
-
Query options.
|
|
2003
|
-
|
|
2004
|
-
**Return:**
|
|
2005
|
-
`Promise<any>` By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc. If you are running a type of query where you don't need the metadata, for example a SELECT query, you can pass in a query type to make sequelize format the results.
|
|
2006
|
-
|
|
2007
|
-
```js
|
|
2008
|
-
// By default the function will return two arguments - a results array, and an object containing metadata (such as amount of affected rows, etc).
|
|
2009
|
-
// Note that since this is a raw query, the metadata are dialect specific.
|
|
2010
|
-
const [results, metadata] = await BookModel.query("UPDATE book SET title = 'Lose Yourself' WHERE id = 1");
|
|
2011
|
-
|
|
2012
|
-
// In cases where you don't need to access the metadata you can pass in a query type to tell sequelize how to format the results. For example, for a simple select query you could do:
|
|
2013
|
-
// We didn't need to destructure the result here - the results were returned directly
|
|
2014
|
-
await BookModel.query("SELECT * FROM book", {type: BookModel.QueryTypes.SELECT});
|
|
2015
|
-
```
|
|
2016
|
-
|
|
2017
|
-
### Authentication
|
|
2018
|
-
EXPRESS SWEET has built-in passport authentication middleware for user authentication by username and password.
|
|
2019
|
-
You can immediately start user authentication in your application using the authentication configuration file and the authentication service module.
|
|
2020
|
-
|
|
2021
|
-
For more information about `passport`, click [here](https://www.passportjs.org/).
|
|
2022
|
-
|
|
2023
|
-
**NOTE:** If an unauthenticated user makes a request to a URL that allows access only if authenticated, the user will be redirected to the page specified by `failure_redirect`.
|
|
2024
|
-
If that access is asynchronous, a `401` error is returned.
|
|
2025
|
-
|
|
2026
|
-
#### Configuration
|
|
2027
|
-
The user authentication configuration is defined in the `config/authentication.js` file.
|
|
2028
|
-
|
|
2029
|
-
Click [here](configuration_sample/esm/authentication.js) to download a sample ESM configuration and
|
|
2030
|
-
[here](configuration_sample/cjs/authentication.js) to download a sample CJS configuration.
|
|
2031
|
-
|
|
2032
|
-
- `enabled: boolean`
|
|
2033
|
-
Set to true to enable user authentication using [Passport middleware](https://www.passportjs.org/docs/).
|
|
2034
|
-
User authentication is enabled (`true`) by default.
|
|
2035
|
-
- `session_store: 'memory'|'redis'`
|
|
2036
|
-
The session store instance, defaults to a new MemoryStore(`memory`) instance.
|
|
2037
|
-
- `cookie_name?: string|undefined`
|
|
2038
|
-
The name of the session ID cookie to set in the response (and read from in the request).
|
|
2039
|
-
The default value is `connect.sid`.
|
|
2040
|
-
- `cookie_secure?: boolean|undefined`
|
|
2041
|
-
Specifies the boolean value for the `Secure` Set-Cookie attribute.
|
|
2042
|
-
The default is `true`, which sets the `Secure` attribute on the cookie.
|
|
2043
|
-
- `cookie_httpOnly?: boolean|undefined`
|
|
2044
|
-
Specifies the boolean value for the `HttpOnly` Set-Cookie attribute.
|
|
2045
|
-
Defaults to `true`, which sets the `HttpOnly` attribute on the cookie.
|
|
2046
|
-
- `redis_host?: string|undefined`
|
|
2047
|
-
If the session is stored in `redis`, this field is required and should be set to the hostname of the Redis server.
|
|
2048
|
-
For example, to connect to redis on localhost on port `6379`, set `redis://localhost:6379`.
|
|
2049
|
-
|
|
2050
|
-
To connect to a different host or port, use a connection string in the format `redis[s]://[[username][:password]@][host][:port][/db-number]`.
|
|
2051
|
-
For example, `redis://alice:foobared@awesome.redis.server:6380`.
|
|
2052
|
-
- `username: string`
|
|
2053
|
-
The login username field name used for authentication.
|
|
2054
|
-
This should be set to the same value as the user field name in the POST body sent to the server and the user example name in the login user table.
|
|
2055
|
-
- `password: string`
|
|
2056
|
-
The login password field name used for authentication.
|
|
2057
|
-
This should be set to the same value as the password field name in the POST body sent to the server and the password column name in the login user table.
|
|
2058
|
-
- `success_redirect: string`
|
|
2059
|
-
The URL to redirect to after successful authentication.
|
|
2060
|
-
The default is the root URL (`/`).
|
|
2061
|
-
- `failure_redirect: string|((req: express.Request, res: express.Response) => string)`
|
|
2062
|
-
Specify the URL to redirect after logging out, or the URL to redirect when the logoff user requests a URL that only the logged-in user can access.
|
|
2063
|
-
This usually specifies the URL of the login page.
|
|
2064
|
-
The default is `/login`.
|
|
2065
|
-
```js
|
|
2066
|
-
// Set the URL to redirect to in case of login failure as a string.
|
|
2067
|
-
failure_redirect: '/login',
|
|
2068
|
-
|
|
2069
|
-
// Dynamically set the url to redirect to on login failure.
|
|
2070
|
-
failure_redirect: (req, res) => {
|
|
2071
|
-
// If the role stored in the cookie is admin, redirect to the admin login screen.
|
|
2072
|
-
return req.cookies.role === 'admin' ? '/adminlogin' : 'login';
|
|
2073
|
-
},
|
|
2074
|
-
```
|
|
2075
|
-
- `authenticate_user: (username: string, password: string, req: express.Request): Promise<object|null>`
|
|
2076
|
-
This hook is called when authenticating a user.
|
|
2077
|
-
Please find the user information that owns the credentials based on the user name and password you received and return it.
|
|
2078
|
-
If the user who owns the credentials cannot be found, return null.
|
|
2079
|
-
|
|
2080
|
-
**NOTE:** Note that the user information must include an ID value that can identify the user.
|
|
2081
|
-
|
|
2082
|
-
The following example uses the user model to find the user who owns the credentials based on the username and password.
|
|
2083
|
-
```js
|
|
2084
|
-
authenticate_user: async (username, password, req) => {
|
|
2085
|
-
const UserModel = require('../models/UserModel');
|
|
2086
|
-
return UserModel.findOne({
|
|
2087
|
-
where: {
|
|
2088
|
-
email: username,
|
|
2089
|
-
password
|
|
2090
|
-
},
|
|
2091
|
-
raw: true
|
|
2092
|
-
});
|
|
2093
|
-
}
|
|
2094
|
-
```
|
|
2095
|
-
- `subscribe_user: (id: number): Promise<object>`
|
|
2096
|
-
This hook is called when user authentication is successful.
|
|
2097
|
-
Please search and return the authenticated user information to be set in the session based on the user ID of the parameter.
|
|
2098
|
-
The returned data will be set in the req.user property and the view's session variable.
|
|
2099
|
-
The following example uses the user model to return the user information that owns the credentials based on the authenticated user's id.
|
|
2100
|
-
```js
|
|
2101
|
-
subscribe_user: async (id) => {
|
|
2102
|
-
const UserModel = require('../models/UserModel');
|
|
2103
|
-
return UserModel.findOne({
|
|
2104
|
-
where: {
|
|
2105
|
-
id
|
|
2106
|
-
},
|
|
2107
|
-
raw: true
|
|
2108
|
-
});
|
|
2109
|
-
}
|
|
2110
|
-
```
|
|
2111
|
-
- `allow_unauthenticated: (string|RegExp)[]`
|
|
2112
|
-
By default, it requires an authenticated user for all requests.
|
|
2113
|
-
You can use the `allow_unauthenticated` option to disable this behavior on certain requests.
|
|
2114
|
-
For example, if you don’t want to authenticate all requests that contain `api` in the URL, set `allow_unauthenticated` as follows.
|
|
2115
|
-
```js
|
|
2116
|
-
allow_unauthenticated: ['/api']
|
|
2117
|
-
```
|
|
2118
|
-
|
|
2119
|
-
You can also use regular expressions.
|
|
2120
|
-
```js
|
|
2121
|
-
allow_unauthenticated: [/^\/api/]
|
|
2122
|
-
```
|
|
2123
|
-
- `expiration: number`
|
|
2124
|
-
Specifies the time, in milliseconds, before the session expires.
|
|
2125
|
-
The default is 24 hours (`86400000` milliseconds).
|
|
2126
|
-
|
|
2127
|
-
#### Login Procedure
|
|
2128
|
-
To authenticate the request, call `services/Authentication.authenticate()` method.
|
|
2129
|
-
This method returns `true` if the authentication succeeds and `false` if it fails.
|
|
2130
|
-
If authentication succeeds, the next handler will be invoked and the `req.user` property will be set to the authenticated user.
|
|
2131
|
-
|
|
2132
|
-
The post-authentication logic depends on whether the login request is received asynchronously or synchronously, so an example of both logics is shown here.
|
|
2133
|
-
|
|
2134
|
-
1. Create a user table to authenticate.
|
|
2135
|
-
```sql
|
|
2136
|
-
CREATE TABLE `user` (
|
|
2137
|
-
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
|
|
2138
|
-
`name` varchar(30) NOT NULL,
|
|
2139
|
-
`email` varchar(255) NOT NULL,
|
|
2140
|
-
`password` varchar(100) NOT NULL,
|
|
2141
|
-
`icon` varchar(768) NOT NULL DEFAULT MD5(RAND()),
|
|
2142
|
-
`created` datetime NOT NULL DEFAULT current_timestamp(),
|
|
2143
|
-
`modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
|
|
2144
|
-
PRIMARY KEY (`id`),
|
|
2145
|
-
UNIQUE KEY `ukUserEmail` (`email`),
|
|
2146
|
-
UNIQUE KEY `ukUserIcon`(`icon`)
|
|
2147
|
-
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
|
2148
|
-
```
|
|
2149
|
-
1. Set the email address and password columns of the user table to be used for authentication in the config file `config/authentication.js`.
|
|
2150
|
-
```js
|
|
2151
|
-
/**
|
|
2152
|
-
* Authentication user ID field name, defaults to `username`.
|
|
2153
|
-
* @type {string}
|
|
2154
|
-
*/
|
|
2155
|
-
username: 'email',
|
|
2156
|
-
|
|
2157
|
-
/**
|
|
2158
|
-
* Authentication password field name, defaults to `password`.
|
|
2159
|
-
* @type {string}
|
|
2160
|
-
*/
|
|
2161
|
-
password: 'password'
|
|
2162
|
-
```
|
|
2163
|
-
1. For asynchronous requests.
|
|
2164
|
-
Returns the authentication result and executes subsequent processing on the front end.
|
|
2165
|
-
|
|
2166
|
-
When the form submits, it sends a login request (`/api/users/login`), and the `routes/api/user.js` router receives the request, authenticates it based on the username and password, and returns the result.
|
|
2167
|
-
After that, the front end checks the authentication result returned from the router and redirects to `/` if the authentication result is successful (`true`).
|
|
2168
|
-
If you redirect to /, the page will automatically switch to the URL specified in `success_redirect` of `config/authentication.js`.
|
|
2169
|
-
```js
|
|
2170
|
-
import {Router} from 'express';
|
|
2171
|
-
import * as expx from 'express-sweet';
|
|
2172
|
-
|
|
2173
|
-
const router = Router();
|
|
2174
|
-
router.post('/login', async (req, res, next) => {
|
|
2175
|
-
const isAuthenticated = await expx.services.Authentication.authenticate(req, res, next);
|
|
2176
|
-
res.json(isAuthenticated);
|
|
1008
|
+
|
|
1009
|
+
res.render('profile', {
|
|
1010
|
+
title: `${user.name}'s Profile`,
|
|
1011
|
+
user,
|
|
1012
|
+
books: userBooks,
|
|
1013
|
+
layout: 'layout/profile'
|
|
2177
1014
|
});
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
<script>
|
|
2189
|
-
const form = document.querySelector('#form');
|
|
2190
|
-
form.addEventListener('submit', async event => {
|
|
2191
|
-
event.preventDefault();
|
|
2192
|
-
const res = await fetch('/api/users/login', {method: 'POST', body: new FormData(form)});
|
|
2193
|
-
const isAuthenticated = await res.json();
|
|
2194
|
-
if (!isAuthenticated)
|
|
2195
|
-
return void alert('The user name or password is incorrect.');
|
|
2196
|
-
location.href = '/';
|
|
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 }
|
|
2197
1025
|
});
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
If it fails, redirect to the page with the URL specified by `failure_redirect` in `config/authentication.js`.
|
|
2203
|
-
```js
|
|
2204
|
-
import {Router} from 'express';
|
|
2205
|
-
import * as expx from 'express-sweet';
|
|
2206
|
-
|
|
2207
|
-
const router = Router();
|
|
2208
|
-
router.post('/login', async (req, res, next) => {
|
|
2209
|
-
const isAuthenticated = await expx.services.Authentication.authenticate(req, res, next);
|
|
2210
|
-
if (isAuthenticated)
|
|
2211
|
-
await expx.services.Authentication.successRedirect(res);
|
|
2212
|
-
else
|
|
2213
|
-
await expx.services.Authentication.failureRedirect(req, res);
|
|
1026
|
+
|
|
1027
|
+
res.render('partials/user-stats', {
|
|
1028
|
+
bookCount,
|
|
1029
|
+
layout: null
|
|
2214
1030
|
});
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
1031
|
+
} catch (error) {
|
|
1032
|
+
next(error);
|
|
1033
|
+
}
|
|
1034
|
+
});
|
|
1035
|
+
|
|
1036
|
+
export default router;
|
|
1037
|
+
```
|
|
1038
|
+
|
|
1039
|
+
### Environment-Specific Configuration
|
|
1040
|
+
|
|
1041
|
+
Configure different settings for development, testing, and production:
|
|
1042
|
+
|
|
1043
|
+
```js
|
|
1044
|
+
// config/config.js
|
|
1045
|
+
const isDevelopment = process.env.NODE_ENV === 'development';
|
|
1046
|
+
const isProduction = process.env.NODE_ENV === 'production';
|
|
1047
|
+
|
|
1048
|
+
export default {
|
|
1049
|
+
env_path: '.env',
|
|
1050
|
+
cors_enabled: isDevelopment,
|
|
1051
|
+
max_body_size: isProduction ? '10mb' : '100mb',
|
|
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
|
+
});
|
|
1068
|
+
}
|
|
1069
|
+
},
|
|
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
|
+
};
|
|
1078
|
+
```
|
|
1079
|
+
|
|
1080
|
+
### Error Handling
|
|
1081
|
+
|
|
1082
|
+
Implement proper error handling in your routes:
|
|
1083
|
+
|
|
2230
1084
|
```js
|
|
2231
1085
|
import {Router} from 'express';
|
|
2232
|
-
import
|
|
1086
|
+
import UserModel from '../models/UserModel.js';
|
|
2233
1087
|
|
|
2234
1088
|
const router = Router();
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
1089
|
+
|
|
1090
|
+
// Route with comprehensive error handling
|
|
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
|
+
}
|
|
2238
1141
|
});
|
|
2239
|
-
export default router;
|
|
2240
|
-
```
|
|
2241
1142
|
|
|
2242
|
-
|
|
2243
|
-
```html
|
|
2244
|
-
<a href="/api/users/logout">Logout</a>
|
|
1143
|
+
export default router;
|
|
2245
1144
|
```
|
|
2246
1145
|
|
|
2247
1146
|
## Release Notes
|
|
2248
|
-
|
|
1147
|
+
|
|
1148
|
+
All changes and version history can be found in the [CHANGELOG.md](CHANGELOG.md).
|
|
2249
1149
|
|
|
2250
1150
|
## Author
|
|
1151
|
+
|
|
2251
1152
|
**Takuya Motoshima**
|
|
2252
1153
|
|
|
2253
1154
|
* [github/takuya-motoshima](https://github.com/takuya-motoshima)
|
|
2254
|
-
* [
|
|
1155
|
+
* [x/takuya_motech](https://x.com/takuya_motech)
|
|
2255
1156
|
* [facebook/takuya.motoshima.7](https://www.facebook.com/takuya.motoshima.7)
|
|
2256
1157
|
|
|
2257
1158
|
## License
|
|
1159
|
+
|
|
2258
1160
|
[MIT](LICENSE)
|