express-sweet 2.0.2 → 2.0.4
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 +76 -9
- package/LICENSE +1 -1
- package/README.md +2193 -20
- package/configuration_sample/cjs/authentication.js +103 -0
- package/configuration_sample/cjs/config.js +74 -0
- package/configuration_sample/cjs/database.js +35 -0
- package/configuration_sample/cjs/view.js +36 -0
- package/configuration_sample/esm/authentication.js +103 -0
- package/configuration_sample/esm/config.js +74 -0
- package/configuration_sample/esm/database.js +35 -0
- package/configuration_sample/esm/view.js +36 -0
- package/dist/build.cjs +22 -22
- package/dist/build.mjs +22 -22
- package/package.json +8 -11
- package/screencaps/belongs-to-many.png +0 -0
- package/screencaps/belongs-to.png +0 -0
- package/screencaps/demonstration.webp +0 -0
- package/screencaps/has-many.png +0 -0
- package/screencaps/has-one.png +0 -0
- package/types/database/Database.d.ts +3 -171
- package/types/database/Model.d.ts +22 -19
- package/types/database/loadModels.d.ts +2 -1
- package/types/handlebars_helpers/array.d.ts +20 -0
- package/types/handlebars_helpers/comparison.d.ts +59 -189
- package/types/handlebars_helpers/date.d.ts +4 -4
- package/types/handlebars_helpers/html.d.ts +3 -3
- package/types/handlebars_helpers/index.d.ts +2 -0
- package/types/handlebars_helpers/layouts.d.ts +21 -0
- package/types/handlebars_helpers/math.d.ts +14 -21
- package/types/handlebars_helpers/number.d.ts +5 -5
- package/types/handlebars_helpers/object.d.ts +4 -4
- package/types/handlebars_helpers/string.d.ts +8 -13
- package/types/interfaces/AuthenticationConfig.d.ts +4 -11
- package/types/interfaces/BasicConfig.d.ts +11 -15
- package/types/interfaces/ViewConfig.d.ts +1 -3
- package/types/middlewares/Authentication.d.ts +3 -1
- package/types/middlewares/CORS.d.ts +3 -1
- package/types/middlewares/Environment.d.ts +3 -3
- package/types/middlewares/ErrorHandler.d.ts +3 -1
- package/types/middlewares/Http.d.ts +3 -1
- package/types/middlewares/Local.d.ts +3 -1
- package/types/middlewares/View.d.ts +6 -2
- package/types/mount.d.ts +3 -2
- package/types/routing/Router.d.ts +3 -1
- package/types/services/Authentication.d.ts +4 -2
- package/types/utils/Types.d.ts +2 -2
- package/types/utils/isAsyncFunction.d.ts +7 -7
- package/types/utils/isFunction.d.ts +8 -8
- package/types/utils/loadAuthenticationConfig.d.ts +2 -2
- package/types/utils/loadBasicConfig.d.ts +2 -2
- package/types/utils/loadDatabaseConfig.d.ts +2 -2
- package/types/utils/loadViewConfig.d.ts +2 -2
- package/INSTALL-Redis.md +0 -77
- package/QUICK_START.md +0 -149
- package/screencaps/login.jpg +0 -0
- package/screencaps/personal.jpg +0 -0
- package/screencaps/user-editing.jpg +0 -0
- package/screencaps/users.jpg +0 -0
package/README.md
CHANGED
|
@@ -1,30 +1,2203 @@
|
|
|
1
|
-
#
|
|
2
|
-
This is an extension of Express.
|
|
1
|
+
# EXPRESS SWEET
|
|
3
2
|
|
|
4
|
-
|
|
5
|
-
- express-sweet V2 Documentation: [https://takuya-motoshima.github.io/express-sweet/v2/](https://takuya-motoshima.github.io/express-sweet/v2/)
|
|
6
|
-
- express-sweet V1 documentation: [https://takuya-motoshima.github.io/express-sweet/v1/](https://takuya-motoshima.github.io/express-sweet/v1/)
|
|
3
|
+
EXPRESS SWEET is a powerful Express.js extension that streamlines your workflow and boosts productivity with a suite of utilities and enhancements.
|
|
7
4
|
|
|
8
|
-
|
|
9
|
-
|
|
5
|
+
- [EXPRESS SWEET](#express-sweet)
|
|
6
|
+
- [EXPRESS SWEET Generator](#express-sweet-generator)
|
|
7
|
+
- [API](#api)
|
|
8
|
+
- [Environment variable](#environment-variable)
|
|
9
|
+
- [Base configuration](#base-configuration)
|
|
10
|
+
- [Routing](#routing)
|
|
11
|
+
- [Basic Routing](#basic-routing)
|
|
12
|
+
- [Nested Routing](#nested-routing)
|
|
13
|
+
- [Default Routing](#default-routing)
|
|
14
|
+
- [Routing Methods](#routing-methods)
|
|
15
|
+
- [View](#view)
|
|
16
|
+
- [Configuration](#configuration)
|
|
17
|
+
- [Syntax](#syntax)
|
|
18
|
+
- [Layout](#layout)
|
|
19
|
+
- [Array Helper](#array-helper)
|
|
20
|
+
- [Comparison Helper](#comparison-helper)
|
|
21
|
+
- [HTML Helper](#html-helper)
|
|
22
|
+
- [Object Helper](#object-helper)
|
|
23
|
+
- [String Helper](#string-helper)
|
|
24
|
+
- [Date Helper](#date-helper)
|
|
25
|
+
- [Number Helper](#number-helper)
|
|
26
|
+
- [Math Helper](#math-helper)
|
|
27
|
+
- [Model](#model)
|
|
28
|
+
- [Configuration](#configuration-1)
|
|
29
|
+
- [Accessing Model](#accessing-model)
|
|
30
|
+
- [Creating Model](#creating-model)
|
|
31
|
+
- [Database class extends sequelize.Sequelize](#database-class-extends-sequelizesequelize)
|
|
32
|
+
- [Instance Methods](#instance-methods)
|
|
33
|
+
- [Model Class extends sequelize.Model](#model-class-extends-sequelizemodel)
|
|
34
|
+
- [Class Properties](#class-properties)
|
|
35
|
+
- [Class Methods](#class-methods)
|
|
36
|
+
- [Authentication](#authentication)
|
|
37
|
+
- [Configuration](#configuration-2)
|
|
38
|
+
- [Login Procedure](#login-procedure)
|
|
39
|
+
- [Logout Procedure](#logout-procedure)
|
|
40
|
+
- [Release Notes](#release-notes)
|
|
41
|
+
- [Author](#author)
|
|
42
|
+
- [License](#license)
|
|
10
43
|
|
|
11
|
-
##
|
|
12
|
-
|
|
44
|
+
## EXPRESS SWEET Generator
|
|
45
|
+
Use the application generator tool, `express-sweet-generator`, to quickly create an application skeleton.
|
|
46
|
+
|
|
47
|
+

|
|
48
|
+
|
|
49
|
+
1. Install and launch the application generator as a global npm package.
|
|
50
|
+
```bash
|
|
51
|
+
npm install -g express-sweet-generator
|
|
52
|
+
```
|
|
53
|
+
1. Display the command options with the -h option.
|
|
54
|
+
```bash
|
|
55
|
+
express-sweet -h
|
|
56
|
+
|
|
57
|
+
Usage: express-sweet [options] [dir]
|
|
58
|
+
|
|
59
|
+
Options:
|
|
60
|
+
|
|
61
|
+
--version output the version number
|
|
62
|
+
-o, --output <output> add output <module> support (esm|cjs) (defaults to cjs)
|
|
63
|
+
-p, --port <port> application listening port (default: 3000)
|
|
64
|
+
-f, --force force on non-empty directory
|
|
65
|
+
-h, --help output usage information
|
|
66
|
+
```
|
|
67
|
+
1. For example, the following creates an Express app named `myapp`. The app will be created in a folder named `myapp` in the current working directory.
|
|
68
|
+
```bash
|
|
69
|
+
express-sweet -o esm myapp
|
|
70
|
+
```
|
|
71
|
+
1. Then install dependencies.
|
|
72
|
+
```bash
|
|
73
|
+
cd myapp/
|
|
74
|
+
npm install
|
|
75
|
+
```
|
|
76
|
+
1. The skeleton uses a DB. Please create a DB with the following SQL.
|
|
77
|
+
```sql
|
|
78
|
+
CREATE DATABASE IF NOT EXISTS `sample_db` DEFAULT CHARACTER SET utf8mb4;
|
|
79
|
+
|
|
80
|
+
USE `sample_db`;
|
|
81
|
+
|
|
82
|
+
CREATE TABLE `user` (
|
|
83
|
+
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
|
|
84
|
+
`name` varchar(30) NOT NULL,
|
|
85
|
+
`email` varchar(255) NOT NULL,
|
|
86
|
+
`password` varchar(100) NOT NULL,
|
|
87
|
+
`icon` varchar(768) NOT NULL DEFAULT MD5(RAND()),
|
|
88
|
+
`created` datetime NOT NULL DEFAULT current_timestamp(),
|
|
89
|
+
`modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
|
|
90
|
+
PRIMARY KEY (`id`),
|
|
91
|
+
UNIQUE KEY `ukUserEmail` (`email`),
|
|
92
|
+
UNIQUE KEY `ukUserIcon`(`icon`)
|
|
93
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
|
94
|
+
|
|
95
|
+
CREATE TABLE `profile` (
|
|
96
|
+
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
|
|
97
|
+
`userId` int(10) unsigned NOT NULL,
|
|
98
|
+
`address` varchar(255) NOT NULL,
|
|
99
|
+
`tel` varchar(14) NOT NULL,
|
|
100
|
+
`created` datetime NOT NULL DEFAULT current_timestamp(),
|
|
101
|
+
`modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
|
|
102
|
+
PRIMARY KEY (`id`),
|
|
103
|
+
UNIQUE KEY `ukProfileUserId` (`userId`),
|
|
104
|
+
CONSTRAINT `fkProfileUser` FOREIGN KEY (`userId`) REFERENCES `user` (`id`)
|
|
105
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
|
106
|
+
|
|
107
|
+
CREATE TABLE `comment` (
|
|
108
|
+
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
|
|
109
|
+
`userId` int(10) unsigned NOT NULL,
|
|
110
|
+
`text` text NOT NULL,
|
|
111
|
+
`created` datetime NOT NULL DEFAULT current_timestamp(),
|
|
112
|
+
`modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
|
|
113
|
+
PRIMARY KEY (`id`),
|
|
114
|
+
CONSTRAINT `fkCommentUser` FOREIGN KEY (`userId`) REFERENCES `user` (`id`)
|
|
115
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
|
116
|
+
|
|
117
|
+
CREATE TABLE `book` (
|
|
118
|
+
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
|
|
119
|
+
`userId` int(10) unsigned NOT NULL,
|
|
120
|
+
`title` text NOT NULL,
|
|
121
|
+
`created` datetime NOT NULL DEFAULT current_timestamp(),
|
|
122
|
+
`modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
|
|
123
|
+
PRIMARY KEY (`id`),
|
|
124
|
+
UNIQUE KEY `ukBookTitle` (`userId`, `title`(255)),
|
|
125
|
+
CONSTRAINT `fkBookUser` FOREIGN KEY (`userId`) REFERENCES `user` (`id`)
|
|
126
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
|
127
|
+
|
|
128
|
+
INSERT INTO `user` (`id`, `email`, `password`, `name`, `icon`) VALUES
|
|
129
|
+
(1, 'robin@example.com', 'password', 'Robin', '/upload/1.png'),
|
|
130
|
+
(2, 'taylor@example.com', 'password', 'Taylor', '/upload/2.png');
|
|
131
|
+
INSERT INTO `profile` (`userId`, `address`, `tel`) VALUES
|
|
132
|
+
(1, '777 Brockton Avenue, Abington MA 2351', '202-555-0105'),
|
|
133
|
+
(2, '30 Memorial Drive, Avon MA 2322', '');
|
|
134
|
+
INSERT INTO `comment` (`userId`, `text`) VALUES
|
|
135
|
+
(1, 'From Robin #1'),
|
|
136
|
+
(1, 'From Robin #2'),
|
|
137
|
+
(2, 'From Taylor #1');
|
|
138
|
+
INSERT INTO `book` (`userId`, `title`) VALUES
|
|
139
|
+
(1, 'Beautiful'),
|
|
140
|
+
(1, 'Lose Yourself'),
|
|
141
|
+
(2, 'When Im Gone');
|
|
142
|
+
```
|
|
143
|
+
1. Set the DB connection method in `config/database.js`. For details, please refer to [here](https://sequelize.org/docs/v6/other-topics/migrations/#cfg).
|
|
144
|
+
```js
|
|
145
|
+
export default {
|
|
146
|
+
development: {
|
|
147
|
+
username: 'root',
|
|
148
|
+
password: 'password',
|
|
149
|
+
database: 'sample_db',
|
|
150
|
+
host: 'localhost',
|
|
151
|
+
dialect: 'mariadb'
|
|
152
|
+
},
|
|
153
|
+
test: {
|
|
154
|
+
username: 'root',
|
|
155
|
+
password: 'password',
|
|
156
|
+
database: 'sample_db',
|
|
157
|
+
host: 'localhost',
|
|
158
|
+
dialect: 'mariadb'
|
|
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
|
+
;
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
### Base configuration
|
|
238
|
+
The basic configuration of EXPRESS SWEET is defined in the `config/config.js` file.
|
|
239
|
+
|
|
240
|
+
Click [here](configuration_sample/esm/config.js) to download a sample ESM configuration
|
|
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.
|
|
318
|
+
```js
|
|
319
|
+
import express from 'express';
|
|
320
|
+
|
|
321
|
+
const app = express();
|
|
322
|
+
app.METHOD(PATH, HANDLER)
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
#### Basic Routing
|
|
326
|
+
All routes are defined in your route files, which are located in the `routes/` directory.
|
|
327
|
+
These files are automatically mapped by `EXPRESS SWEET` to the route files specified in the URI and the route handlers defined in the route files.
|
|
328
|
+
The following examples illustrate defining simple routes.
|
|
329
|
+
`routes/user.js` responds to `GET /user` requests.
|
|
330
|
+
```js
|
|
331
|
+
import {Router} from 'express';
|
|
332
|
+
|
|
333
|
+
const router = Router();
|
|
334
|
+
router.get('/', (req, res) => {
|
|
335
|
+
res.send('Hello World');
|
|
336
|
+
});
|
|
337
|
+
export default router;
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
#### Nested Routing
|
|
341
|
+
The router supports nested files.
|
|
342
|
+
If you create a nested folder structure files will be automatically routed in the same way still.
|
|
343
|
+
`routes/api/users.js` responds to `GET /api/users` requests.
|
|
344
|
+
```js
|
|
345
|
+
import {Router} from 'express';
|
|
346
|
+
|
|
347
|
+
const router = Router();
|
|
348
|
+
router.get('/', (req, res) => {
|
|
349
|
+
res.send('Hello World');
|
|
350
|
+
});
|
|
351
|
+
export default router;
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
#### Default Routing
|
|
355
|
+
EXPRESS SWEET can be told to load a default router when a URI is not present, as will be the case when only your site root URL (`/`) is requested.
|
|
356
|
+
To specify a default router, open your `config/config.js` file and set this variable:
|
|
357
|
+
```js
|
|
358
|
+
default_router: '/blog'
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
Where blog is the name of the router module you want used.
|
|
362
|
+
Next, create the `routes/blog.js` module.
|
|
363
|
+
```js
|
|
364
|
+
import {Router} from 'express';
|
|
365
|
+
|
|
366
|
+
const router = Router();
|
|
367
|
+
router.get('/', (req, res) => {
|
|
368
|
+
res.send('Hello World');
|
|
369
|
+
});
|
|
370
|
+
export default router;
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
Now when you request the root URL (`/`), you will see "Hello World".
|
|
374
|
+
|
|
375
|
+
#### Routing Methods
|
|
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
|
+
```
|
|
438
|
+
|
|
439
|
+
#### Syntax
|
|
440
|
+
To mark where layout should insert page.
|
|
441
|
+
```js
|
|
442
|
+
{{{body}}}
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
To declare a block placeholder in layout.
|
|
446
|
+
```js
|
|
447
|
+
{{{block "script"}}}
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
To define block content in a page.
|
|
451
|
+
```js
|
|
452
|
+
{{#contentFor "script"}}
|
|
453
|
+
CONTENT HERE
|
|
454
|
+
{{/contentFor}}
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
#### Layout
|
|
458
|
+
There are three ways to use a layout, listed in precedence order.
|
|
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
|
+
#### Object Helper
|
|
846
|
+
- `jsonStringify()`
|
|
847
|
+
Stringify an object using JSON.stringify.
|
|
848
|
+
|
|
849
|
+
**Parameters:**
|
|
850
|
+
- val: any
|
|
851
|
+
The value to convert to a JSON string.
|
|
852
|
+
- indent: number
|
|
853
|
+
The number of space characters to use as whitespace.
|
|
854
|
+
|
|
855
|
+
**Return:**
|
|
856
|
+
`string` A JSON string representing the given value, or undefined.
|
|
857
|
+
|
|
858
|
+
```js
|
|
859
|
+
{{jsonStringify val}}
|
|
860
|
+
```
|
|
861
|
+
- `jsonParse()`
|
|
862
|
+
Parses the given string using JSON.parse.
|
|
863
|
+
|
|
864
|
+
**Parameters:**
|
|
865
|
+
- val: any
|
|
866
|
+
Object to stringify.
|
|
867
|
+
|
|
868
|
+
**Return:**
|
|
869
|
+
`any` JavaScript value or object described by a string.
|
|
870
|
+
|
|
871
|
+
```js
|
|
872
|
+
{{jsonParse val}}
|
|
873
|
+
```
|
|
874
|
+
|
|
875
|
+
#### String Helper
|
|
876
|
+
- `replace()`
|
|
877
|
+
Returns a new string with some or all matches of a pattern replaced by a replacement.
|
|
878
|
+
|
|
879
|
+
**Parameters:**
|
|
880
|
+
- val: string
|
|
881
|
+
String.
|
|
882
|
+
- find: string
|
|
883
|
+
The string to be replaced.
|
|
884
|
+
- replace: string
|
|
885
|
+
The string to replace.
|
|
886
|
+
|
|
887
|
+
**Return:**
|
|
888
|
+
`string` Character string after replacement.
|
|
889
|
+
|
|
890
|
+
```js
|
|
891
|
+
{{replace 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?' 'dog' 'monkey'}}
|
|
892
|
+
```
|
|
893
|
+
- `split()`
|
|
894
|
+
Split `string` by the given `character`.
|
|
895
|
+
|
|
896
|
+
**Parameters:**
|
|
897
|
+
- val: string
|
|
898
|
+
String.
|
|
899
|
+
- separator: string
|
|
900
|
+
A character that delimits the substrings in this string. Default is a comma.
|
|
901
|
+
|
|
902
|
+
**Return:**
|
|
903
|
+
`string[]` An Array of strings, split at each point where the separator occurs in the given string. The default is a comma.
|
|
904
|
+
|
|
905
|
+
```js
|
|
906
|
+
{{split "a,b,c" ","}}
|
|
907
|
+
{{#each (split list ',')}}<div>{{this}}</div>{{/each}}
|
|
908
|
+
```
|
|
909
|
+
- `formatBytes()`
|
|
910
|
+
Convert bytes to just the right units(KB, MB, GB, TB, PB, EB, ZB, YB).
|
|
911
|
+
|
|
912
|
+
**Parameters:**
|
|
913
|
+
- bytes: number
|
|
914
|
+
Bytes.
|
|
915
|
+
- decimals?: number
|
|
916
|
+
Number of decimal places to display. Default is 0.
|
|
917
|
+
|
|
918
|
+
**Return:**
|
|
919
|
+
`string` Returns a value with units.
|
|
920
|
+
|
|
921
|
+
```js
|
|
922
|
+
{{!-- results in: 1 KB --}}
|
|
923
|
+
{{formatBytes 1024}}
|
|
924
|
+
|
|
925
|
+
{{!-- results in: 1.21 KB --}}
|
|
926
|
+
{{formatBytes 1234 2}}
|
|
927
|
+
|
|
928
|
+
{{!-- results in: 1.205 KB --}}
|
|
929
|
+
{{formatBytes 1234 3}}
|
|
930
|
+
|
|
931
|
+
{{!-- results in: 0 Bytes --}}
|
|
932
|
+
{{formatBytes 0}}
|
|
933
|
+
```
|
|
934
|
+
|
|
935
|
+
#### Date Helper
|
|
936
|
+
- `formatDate()`
|
|
937
|
+
Use moment to format the date.
|
|
938
|
+
|
|
939
|
+
**Parameters:**
|
|
940
|
+
- format: string
|
|
941
|
+
A format string based on `moment`.
|
|
942
|
+
- date: string
|
|
943
|
+
Date string to format.
|
|
944
|
+
- locale: string|string[]
|
|
945
|
+
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).
|
|
946
|
+
|
|
947
|
+
**Return:**
|
|
948
|
+
`string` Returns formatted date.
|
|
949
|
+
|
|
950
|
+
```js
|
|
951
|
+
{{!-- results in: 2021/10/24 --}}
|
|
952
|
+
{{formatDate 'YYYY/MM/DD' "2021-10-24T02:13:06.610Z"}}
|
|
953
|
+
|
|
954
|
+
{{!-- results in: 2021/10/24 --}}
|
|
955
|
+
{{formatDate 'YYYY/MM/DD' "2021-10-24T02:13:06.610Z" 'jp'}}
|
|
956
|
+
|
|
957
|
+
{{!-- results in: 2021/10/24 --}}
|
|
958
|
+
{{formatDate 'YYYY/MM/DD' "2021-10-24T02:13:06.610Z" 'es'}}
|
|
959
|
+
```
|
|
960
|
+
|
|
961
|
+
#### Number Helper
|
|
962
|
+
- `number2locale()`
|
|
963
|
+
Returns the language-sensitive representation of a number as a string.
|
|
964
|
+
|
|
965
|
+
**Parameters:**
|
|
966
|
+
- val: number|string
|
|
967
|
+
Target number or numeric string.
|
|
968
|
+
- locales: string|undefined
|
|
969
|
+
A string with a BCP 47 language tag, or an array of such strings.
|
|
970
|
+
Corresponds to the `locales` parameter of the Intl.NumberFormat() constructor.
|
|
971
|
+
In implementations without Intl.NumberFormat support, this parameter is ignored and the host's locale is usually used.
|
|
972
|
+
|
|
973
|
+
**Return:**
|
|
974
|
+
`string` A string with a language-sensitive representation of the given number.
|
|
975
|
+
|
|
976
|
+
```js
|
|
977
|
+
{{!-- results in: 123,456.789 --}}
|
|
978
|
+
{{number2locale 123456.789}}
|
|
979
|
+
|
|
980
|
+
{{!-- German uses comma as decimal separator and period for thousands. --}}
|
|
981
|
+
{{!-- results in: 123.456,789 --}}
|
|
982
|
+
{{number2locale 123456.789 'de-DE'}}
|
|
983
|
+
```
|
|
984
|
+
|
|
985
|
+
#### Math Helper
|
|
986
|
+
- `add()`
|
|
987
|
+
Calculates the sum of two numbers.
|
|
988
|
+
|
|
989
|
+
**Parameters:**
|
|
990
|
+
- val1: number|string
|
|
991
|
+
The first number.
|
|
992
|
+
- val2: number|string
|
|
993
|
+
The second number.
|
|
994
|
+
|
|
995
|
+
**Return:**
|
|
996
|
+
`number`
|
|
997
|
+
|
|
998
|
+
```js
|
|
999
|
+
{{add 1 2}}
|
|
1000
|
+
```
|
|
1001
|
+
- `sub()`
|
|
1002
|
+
Calculates the difference of the given values.
|
|
1003
|
+
|
|
1004
|
+
**Parameters:**
|
|
1005
|
+
- val1: number|string
|
|
1006
|
+
The first number.
|
|
1007
|
+
- val2: number|string
|
|
1008
|
+
The second number.
|
|
1009
|
+
|
|
1010
|
+
**Return:**
|
|
1011
|
+
`number`
|
|
1012
|
+
|
|
1013
|
+
```js
|
|
1014
|
+
{{sub 5 2}}
|
|
1015
|
+
```
|
|
1016
|
+
- `multiply()`
|
|
1017
|
+
Calculate the multiplication of the given values.
|
|
1018
|
+
|
|
1019
|
+
**Parameters:**
|
|
1020
|
+
- val1: number|string
|
|
1021
|
+
The first number.
|
|
1022
|
+
- val2: number|string
|
|
1023
|
+
The second number.
|
|
1024
|
+
|
|
1025
|
+
**Return:**
|
|
1026
|
+
`number`
|
|
1027
|
+
|
|
1028
|
+
```js
|
|
1029
|
+
{{multiply 5 2}}
|
|
1030
|
+
```
|
|
1031
|
+
- `divide()`
|
|
1032
|
+
Compute the division of the given values.
|
|
1033
|
+
|
|
1034
|
+
**Parameters:**
|
|
1035
|
+
- val1: number|string
|
|
1036
|
+
The first number.
|
|
1037
|
+
- val2: number|string
|
|
1038
|
+
The second number.
|
|
1039
|
+
|
|
1040
|
+
**Return:**
|
|
1041
|
+
`number`
|
|
1042
|
+
|
|
1043
|
+
```js
|
|
1044
|
+
{{divide 10 2}}
|
|
1045
|
+
```
|
|
1046
|
+
- `ceil()`
|
|
1047
|
+
Round up the value.
|
|
1048
|
+
|
|
1049
|
+
**Parameters:**
|
|
1050
|
+
- val: number|string
|
|
1051
|
+
Number to be rounded to nearest greater integer.
|
|
1052
|
+
|
|
1053
|
+
**Return:**
|
|
1054
|
+
`number`
|
|
1055
|
+
|
|
1056
|
+
```js
|
|
1057
|
+
{{ceil 5.6}}
|
|
1058
|
+
```
|
|
1059
|
+
- `floor()`
|
|
1060
|
+
Rounds down a number.
|
|
1061
|
+
|
|
1062
|
+
**Parameters:**
|
|
1063
|
+
- val: number|string
|
|
1064
|
+
Number to be rounded to nearest lower integer.
|
|
1065
|
+
|
|
1066
|
+
**Return:**
|
|
1067
|
+
`number`
|
|
1068
|
+
|
|
1069
|
+
```js
|
|
1070
|
+
{{floor 5.6}}
|
|
1071
|
+
```
|
|
1072
|
+
- `abs()`
|
|
1073
|
+
Returns an absolute value.
|
|
1074
|
+
|
|
1075
|
+
**Parameters:**
|
|
1076
|
+
- val: number|string
|
|
1077
|
+
Number to perform absolute value operation on.
|
|
1078
|
+
|
|
1079
|
+
**Return:**
|
|
1080
|
+
`number`
|
|
1081
|
+
|
|
1082
|
+
```js
|
|
1083
|
+
{{abs -5.6}}
|
|
1084
|
+
```
|
|
1085
|
+
|
|
1086
|
+
### Model
|
|
1087
|
+
Models provide a way to interact with a specific table in your database.
|
|
1088
|
+
EXPRESS SWEET provides a [Sequelize](https://sequelize.org/docs/v6/) based model class that offers some great features, including.
|
|
1089
|
+
- Automatic database connection.
|
|
1090
|
+
- Basic CRUD methods.
|
|
1091
|
+
- And more.
|
|
1092
|
+
|
|
1093
|
+
This class provides a solid base from which to build your own models, allowing you to rapidly build out your application’s model layer.
|
|
1094
|
+
|
|
1095
|
+
#### Configuration
|
|
1096
|
+
The database configuration is defined in the `config/database.js` file.
|
|
1097
|
+
|
|
1098
|
+
Click [here](configuration_sample/esm/database.js) to download a sample ESM configuration
|
|
1099
|
+
and [here](configuration_sample/cjs/database.js) to download a sample CJS configuration.
|
|
1100
|
+
|
|
1101
|
+
- `username: string`
|
|
1102
|
+
The username which is used to authenticate against the database.
|
|
1103
|
+
- `password: string|null`
|
|
1104
|
+
The password which is used to authenticate against the database.
|
|
1105
|
+
The default is no password (`null`).
|
|
1106
|
+
- `database: string`
|
|
1107
|
+
The name of the database.
|
|
1108
|
+
- `host: string`
|
|
1109
|
+
The host of the relational database.
|
|
1110
|
+
- `port: number|null`
|
|
1111
|
+
The port of the relational database.
|
|
1112
|
+
The default is automatic selection (`null`).
|
|
1113
|
+
- `dialect: string`
|
|
1114
|
+
The dialect of the database you are connecting to.
|
|
1115
|
+
One of `mariadb`, `mysql`, `postgres`, `sqlite` and `mssql`.
|
|
1116
|
+
- `logging: boolean|(...message: any[]) => void`
|
|
1117
|
+
Set true to output the executed query etc. to the log.
|
|
1118
|
+
The default is no log output (`false`).
|
|
1119
|
+
- `timezone: string`
|
|
1120
|
+
Time zone dedicated to writing to the database.
|
|
1121
|
+
For example, for the Japanese time zone, do the following.
|
|
1122
|
+
```js
|
|
1123
|
+
timezone: '+09:00'
|
|
1124
|
+
```
|
|
1125
|
+
|
|
1126
|
+
#### Accessing Model
|
|
1127
|
+
Place the model in the `models/` directory of the root directory.
|
|
1128
|
+
When you load the model, you have immediate access to the model's functions for working with the database.
|
|
1129
|
+
|
|
1130
|
+
```js
|
|
1131
|
+
import BookModel from '../models/BookModel';
|
|
1132
|
+
|
|
1133
|
+
// INSERT INTO book (title) VALUES ('Beautiful')
|
|
1134
|
+
await BookModel.create({title: 'Beautiful'});
|
|
1135
|
+
|
|
1136
|
+
// SELECT * FROM book
|
|
1137
|
+
await BookModel.findAll();
|
|
1138
|
+
|
|
1139
|
+
// UPDATE book SET title = 'Beautiful' WHERE id= 1
|
|
1140
|
+
await BookModel.update({title: 'Beautiful'}, {where: {id: 1}});
|
|
1141
|
+
|
|
1142
|
+
// DELETE FROM book WHERE id= 1
|
|
1143
|
+
await BookModel.destroy({where: {id: 1}});
|
|
1144
|
+
```
|
|
1145
|
+
|
|
1146
|
+
#### Creating Model
|
|
1147
|
+
To take advantage of EXPRESS SWEET’s model, you would simply create a new model class that extends `database/Model`.
|
|
1148
|
+
This class provides convenient access to the database connection, the Query Builder, and a number of additional convenience methods.
|
|
1149
|
+
For more information, see [reference](#model-class).
|
|
1150
|
+
```js
|
|
1151
|
+
import * as expressExtension from 'express-sweet';
|
|
1152
|
+
|
|
1153
|
+
export default class extends expressExtension.database.Model {
|
|
1154
|
+
static get table() {
|
|
1155
|
+
return 'user';
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
static get attributes() {
|
|
1159
|
+
return {
|
|
1160
|
+
id: {
|
|
1161
|
+
type: this.DataTypes.INTEGER,
|
|
1162
|
+
primaryKey: true,
|
|
1163
|
+
autoIncrement: true
|
|
1164
|
+
},
|
|
1165
|
+
name: this.DataTypes.STRING,
|
|
1166
|
+
email: this.DataTypes.STRING,
|
|
1167
|
+
password: this.DataTypes.STRING,
|
|
1168
|
+
icon: this.DataTypes.STRING,
|
|
1169
|
+
created: this.DataTypes.DATE,
|
|
1170
|
+
modified: this.DataTypes.DATE
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
```
|
|
1175
|
+
|
|
1176
|
+
#### Database class extends [sequelize.Sequelize](https://sequelize.org/api/v6/class/src/sequelize.js~sequelize)
|
|
1177
|
+
This is the class that makes the database connection.
|
|
1178
|
+
See [here](https://sequelize.org/api/v6/class/src/sequelize.js~sequelize) for other available methods.
|
|
1179
|
+
|
|
1180
|
+
The database connection is automatic when the model is loaded.
|
|
1181
|
+
The configuration related to the database connection is defined in the `config/database.js` file.
|
|
1182
|
+
For more information on database configuration, see [Database configuration](#configuration-1).
|
|
1183
|
+
|
|
1184
|
+
##### Instance Methods
|
|
1185
|
+
- `public constructor()`
|
|
1186
|
+
Instantiate sequelize with name of database, username and password.
|
|
1187
|
+
- `public isConnect()`
|
|
1188
|
+
Test the connection by trying to authenticate. It runs `SELECT 1+1 AS result` query.
|
|
1189
|
+
|
|
1190
|
+
**Return:**
|
|
1191
|
+
`Promise<boolean>` Returns `true` if it can connect to the database, `false` if it cannot.
|
|
1192
|
+
|
|
1193
|
+
```js
|
|
1194
|
+
import * as expressExtension from 'express-sweet';
|
|
1195
|
+
|
|
1196
|
+
await expressExtension.database.Database.isConnect();
|
|
1197
|
+
```
|
|
1198
|
+
|
|
1199
|
+
#### Model Class extends [sequelize.Model](https://sequelize.org/api/v6/class/src/model.js~model)
|
|
1200
|
+
This is a class that abstracts the tables in the database.
|
|
1201
|
+
See [here](https://sequelize.org/api/v6/class/src/model.js~model) for more information on the methods and properties available in your model.
|
|
1202
|
+
|
|
1203
|
+
##### Class Properties
|
|
1204
|
+
- `protected static table: string`
|
|
1205
|
+
The name of the table that the model accesses. This member must be defined in a subclass.
|
|
1206
|
+
```js
|
|
1207
|
+
import * as expressExtension from 'express-sweet';
|
|
1208
|
+
|
|
1209
|
+
export default class extends expressExtension.database.Model {
|
|
1210
|
+
static get table() {
|
|
1211
|
+
return 'user';
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
```
|
|
1215
|
+
- `protected static attributes: sequelize.ModelAttributes`
|
|
1216
|
+
List of columns in the table accessed by this model. This member must be defined in a subclass.
|
|
1217
|
+
```js
|
|
1218
|
+
import * as expressExtension from 'express-sweet';
|
|
1219
|
+
|
|
1220
|
+
export default class extends expressExtension.database.Model {
|
|
1221
|
+
static get attributes() {
|
|
1222
|
+
return {
|
|
1223
|
+
id: {
|
|
1224
|
+
type: this.DataTypes.INTEGER,
|
|
1225
|
+
primaryKey: true,
|
|
1226
|
+
autoIncrement: true
|
|
1227
|
+
},
|
|
1228
|
+
name: this.DataTypes.STRING,
|
|
1229
|
+
email: this.DataTypes.STRING,
|
|
1230
|
+
password: this.DataTypes.STRING,
|
|
1231
|
+
icon: this.DataTypes.STRING,
|
|
1232
|
+
created: this.DataTypes.DATE,
|
|
1233
|
+
modified: this.DataTypes.DATE
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
```
|
|
1238
|
+
- `public static readonly DataTypes: {[key: string]: any}`
|
|
1239
|
+
A convenience class holding commonly used data types.
|
|
1240
|
+
This is an alias for `sequelize.DataTypes`.
|
|
1241
|
+
See [here](https://sequelize.org/api/v6/variable/index.html#static-variable-DataTypes) for details.
|
|
1242
|
+
```js
|
|
1243
|
+
{id: this.DataTypes.INTEGER}
|
|
1244
|
+
```
|
|
1245
|
+
- `public static readonly Op: {[key: string]: any}`
|
|
1246
|
+
Operator symbols to be used when querying data.
|
|
1247
|
+
This is an alias for `sequelize.Op`.
|
|
1248
|
+
See [here](https://sequelize.org/docs/v6/core-concepts/model-querying-basics/#operators) for details.
|
|
1249
|
+
```js
|
|
1250
|
+
import BookModel from '../models/BookModel';
|
|
1251
|
+
|
|
1252
|
+
// SELECT * FROM book WHERE title = 'Beautiful' AND genre = 'Nonfiction';
|
|
1253
|
+
BookModel.findOne({
|
|
1254
|
+
where: {
|
|
1255
|
+
[BookModel.Op.and]: [
|
|
1256
|
+
{title: 'Beautiful'},
|
|
1257
|
+
{genre: 'Nonfiction'}
|
|
1258
|
+
]
|
|
1259
|
+
}
|
|
1260
|
+
});
|
|
1261
|
+
|
|
1262
|
+
// SELECT * FROM book WHERE title = 'Beautiful' OR title = 'Lose Yourself';
|
|
1263
|
+
BookModel.findAll({
|
|
1264
|
+
where: {
|
|
1265
|
+
[BookModel.Op.or]: [
|
|
1266
|
+
{title: 'Beautiful'},
|
|
1267
|
+
{title: 'Lose Yourself'}
|
|
1268
|
+
]
|
|
1269
|
+
}
|
|
1270
|
+
});
|
|
1271
|
+
|
|
1272
|
+
// DELETE FROM user WHERE name = 'Beautiful' OR name = 'Lose Yourself';
|
|
1273
|
+
BookModel.destroy({
|
|
1274
|
+
where: {
|
|
1275
|
+
title: {[BookModel.Op.or]: ['Beautiful', 'Lose Yourself']}
|
|
1276
|
+
}
|
|
1277
|
+
});
|
|
1278
|
+
```
|
|
1279
|
+
- `public static readonly fn: (fn: string, ...args: unknown[]) => any`
|
|
1280
|
+
Creates an object representing a database function.
|
|
1281
|
+
This can be used in search queries, both in where and order parts, and as default values in column definitions.
|
|
1282
|
+
If you want to refer to columns in your function, you should use sequelize.col, so that the columns are properly interpreted as columns and not a strings.
|
|
1283
|
+
See [here](https://sequelize.org/api/v6/class/src/sequelize.js~sequelize#static-method-fn) for details.
|
|
1284
|
+
```js
|
|
1285
|
+
import BookModel from '../models/BookModel';
|
|
1286
|
+
|
|
1287
|
+
// SELECT upper(`title`) AS `title` FROM `book` AS `book`;
|
|
1288
|
+
const books = await BookModel.findAll({
|
|
1289
|
+
attributes: [[BookModel.fn('upper', BookModel.col('title')), 'title']],
|
|
1290
|
+
raw: true
|
|
1291
|
+
});
|
|
1292
|
+
```
|
|
1293
|
+
- `public static readonly col: (col: string) => any`
|
|
1294
|
+
Creates an object which represents a column in the DB, this allows referencing another column in your query.
|
|
1295
|
+
This is often useful in conjunction with sequelize.fn, since raw string arguments to fn will be escaped.
|
|
1296
|
+
See [here](https://sequelize.org/api/v6/class/src/sequelize.js~sequelize#static-method-col) for details.
|
|
1297
|
+
- `public static readonly literal: (val: string) => any`
|
|
1298
|
+
Creates an object representing a literal, i.e. something that will not be escaped.
|
|
1299
|
+
See [here](https://sequelize.org/api/v6/class/src/sequelize.js~sequelize#static-method-literal) for details.
|
|
1300
|
+
```js
|
|
1301
|
+
import BookModel from '../models/BookModel';
|
|
1302
|
+
|
|
1303
|
+
// SELECT `id`, `title`, (SELECT COUNT(*) FROM comment WHERE comment.bookId = book.id) AS `count` FROM `book` AS `book`;
|
|
1304
|
+
const books = await BookModel.findAll({
|
|
1305
|
+
attributes: [
|
|
1306
|
+
'id',
|
|
1307
|
+
'title',
|
|
1308
|
+
[BookModel.literal(`(SELECT COUNT(*) FROM comment WHERE comment.bookId = book.id)`), 'count']
|
|
1309
|
+
],
|
|
1310
|
+
raw: true
|
|
1311
|
+
});
|
|
1312
|
+
```
|
|
1313
|
+
- `public static readonly where: (attr: sequelize.AttributeType, comparator: string, logic: sequelize.LogicType) => sequelize.Utils.Where`
|
|
1314
|
+
A way of specifying attr = condition.
|
|
1315
|
+
The attr can either be an object taken from Model.rawAttributes (for example Model.rawAttributes.id or Model.rawAttributes.name).
|
|
1316
|
+
The attribute should be defined in your model definition.
|
|
1317
|
+
The attribute can also be an object from one of the sequelize utility functions (sequelize.fn, sequelize.col etc.)
|
|
1318
|
+
For string attributes, use the regular {where: {attr: something}} syntax.
|
|
1319
|
+
If you don't want your string to be escaped, use sequelize.literal.
|
|
1320
|
+
See [here](https://sequelize.org/api/v6/class/src/sequelize.js~sequelize#static-method-where) for details.
|
|
1321
|
+
```js
|
|
1322
|
+
import BookModel from '../models/BookModel';
|
|
1323
|
+
|
|
1324
|
+
// SELECT `title` FROM `book` AS `book` WHERE CHAR_LENGTH(`title`) <= 10;
|
|
1325
|
+
const books = await BookModel.findAll({
|
|
1326
|
+
attributes: ['title'],
|
|
1327
|
+
where: BookModel.where(
|
|
1328
|
+
BookModel.fn('CHAR_LENGTH', BookModel.col('title')),
|
|
1329
|
+
{[BookModel.Op.lte]: 10}
|
|
1330
|
+
),
|
|
1331
|
+
raw: true
|
|
1332
|
+
});
|
|
1333
|
+
```
|
|
1334
|
+
- `public static readonly QueryTypes: {[key: string]: string}`
|
|
1335
|
+
An enum of query types used by `sequelize.query`.
|
|
1336
|
+
See [here](https://sequelize.org/api/v6/variable/index.html#static-variable-QueryTypes) for details.
|
|
1337
|
+
- `public static readonly Transaction: (typeof sequelize.Transaction)`
|
|
1338
|
+
Reference to [sequelize.Transaction](https://sequelize.org/api/v6/class/src/transaction.js~transaction).
|
|
1339
|
+
This includes properties such as isolation level enums used with the transaction option.
|
|
1340
|
+
```js
|
|
1341
|
+
const BookModel = require('../models/BookModel');
|
|
1342
|
+
BookModel.Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED // "READ UNCOMMITTED"
|
|
1343
|
+
BookModel.Transaction.ISOLATION_LEVELS.READ_COMMITTED // "READ COMMITTED"
|
|
1344
|
+
BookModel.Transaction.ISOLATION_LEVELS.REPEATABLE_READ // "REPEATABLE READ"
|
|
1345
|
+
BookModel.Transaction.ISOLATION_LEVELS.SERIALIZABLE // "SERIALIZABLE"
|
|
1346
|
+
```
|
|
1347
|
+
|
|
1348
|
+
##### Class Methods
|
|
1349
|
+
- `public static association()`
|
|
1350
|
+
Associate the model.
|
|
1351
|
+
Define associations with other models such as `hasOne`, `hasMany`, `belongsTo`, `belongsToMany`.
|
|
1352
|
+
This method is called automatically from within the `mount` method, so you don't have to run it yourself.
|
|
1353
|
+
See the [here](https://sequelize.org/api/v6/class/src/associations/base.js~association) for more information.
|
|
1354
|
+
If you omit the alias (`as`) option, the associated name will be hasOne, singular for belongsTo, and plural for hasMany.
|
|
1355
|
+
```js
|
|
1356
|
+
import * as expressExtension from 'express-sweet';
|
|
1357
|
+
import ProfileModel from './ProfileModel';
|
|
1358
|
+
|
|
1359
|
+
export default class extends expressExtension.database.Model {
|
|
1360
|
+
static association() {
|
|
1361
|
+
// User has one profile.
|
|
1362
|
+
this.hasOne(ProfileModel, {
|
|
1363
|
+
foreignKey: 'userId', // profile.userId
|
|
1364
|
+
sourceKey: 'id', // user.id
|
|
1365
|
+
as: 'profile'
|
|
1366
|
+
});
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
```
|
|
1370
|
+
- `public static begin()`
|
|
1371
|
+
Starts a transaction and returns a transaction object to identify the running transaction.
|
|
1372
|
+
This is an alias for the `sequelize.Sequelize.transaction()` method.
|
|
1373
|
+
See [here](https://sequelize.org/api/v6/class/src/sequelize.js~sequelize#instance-method-transaction) for details.
|
|
1374
|
+
|
|
1375
|
+
**Parameters:**
|
|
1376
|
+
- options?: sequelize.TransactionOptions
|
|
1377
|
+
Options provided when the transaction is created.
|
|
1378
|
+
|
|
1379
|
+
**Return:**
|
|
1380
|
+
`Promise<sequelize.Transaction>` Returns a transaction object to identify the transaction being executed.
|
|
1381
|
+
|
|
1382
|
+
Simple transaction usage example.
|
|
1383
|
+
```js
|
|
1384
|
+
import BookModel from '../models/BookModel';
|
|
1385
|
+
|
|
1386
|
+
let transaction;
|
|
1387
|
+
try {
|
|
1388
|
+
transaction = await BookModel.begin();
|
|
1389
|
+
const book = await BookModel.create({title: 'Beautiful'}, {transaction});
|
|
1390
|
+
await transaction.commit();
|
|
1391
|
+
} catch {
|
|
1392
|
+
if (transaction)
|
|
1393
|
+
await transaction.rollback();
|
|
1394
|
+
}
|
|
1395
|
+
```
|
|
1396
|
+
|
|
1397
|
+
You can also use transaction options.
|
|
1398
|
+
```js
|
|
1399
|
+
import BookModel from '../models/BookModel';
|
|
1400
|
+
|
|
1401
|
+
let transaction;
|
|
1402
|
+
try {
|
|
1403
|
+
transaction = await BookModel.begin({
|
|
1404
|
+
isolationLevel: BookModel.Transaction.ISOLATION_LEVELS.REPEATABLE_READ,
|
|
1405
|
+
type: BookModel.Transaction.TYPES.DEFERRED,
|
|
1406
|
+
});
|
|
1407
|
+
const book = await BookModel.findOne({where: {id: 1}}, {transaction});
|
|
1408
|
+
book.title = 'Beautiful';
|
|
1409
|
+
await book.save({transaction});
|
|
1410
|
+
await transaction.commit();
|
|
1411
|
+
|
|
1412
|
+
// Load updated data.
|
|
1413
|
+
await book.reload();
|
|
1414
|
+
} catch {
|
|
1415
|
+
if (transaction)
|
|
1416
|
+
await transaction.rollback();
|
|
1417
|
+
}
|
|
1418
|
+
```
|
|
1419
|
+
- `public static create()`
|
|
1420
|
+
Builds a new model instance and calls `save` on it.
|
|
1421
|
+
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-create) for details.
|
|
1422
|
+
|
|
1423
|
+
**Parameters:**
|
|
1424
|
+
- values: object
|
|
1425
|
+
Hash of data values to create new record with.
|
|
1426
|
+
- options: object
|
|
1427
|
+
Build and query options.
|
|
1428
|
+
|
|
1429
|
+
**Return:**
|
|
1430
|
+
`Promise<Model>` Returns a model that contains the data for the added record.
|
|
1431
|
+
|
|
1432
|
+
```js
|
|
1433
|
+
import BookModel from '../models/BookModel';
|
|
1434
|
+
|
|
1435
|
+
// INSERT INTO `book` (`id`,`title`) VALUES (DEFAULT,'Beautiful');
|
|
1436
|
+
await BookModel.create({title: 'Beautiful'});
|
|
1437
|
+
```
|
|
1438
|
+
- `public static save()`
|
|
1439
|
+
Validates this instance, and if the validation passes, persists it to the database.
|
|
1440
|
+
See [here](https://sequelize.org/api/v6/class/src/model.js~model#instance-method-save) for details.
|
|
1441
|
+
|
|
1442
|
+
**Parameters:**
|
|
1443
|
+
- options: object
|
|
1444
|
+
save options.
|
|
1445
|
+
|
|
1446
|
+
**Return:**
|
|
1447
|
+
`Promise<Model>` Returns a model that contains data for manipulated records such as add and update.
|
|
1448
|
+
|
|
1449
|
+
```js
|
|
1450
|
+
import BookModel from '../models/BookModel';
|
|
1451
|
+
|
|
1452
|
+
// INSERT INTO `book` (`id`,`title`) VALUES (DEFAULT,'Beautiful');
|
|
1453
|
+
const book = BookModel.build({title: 'Beautiful'});
|
|
1454
|
+
await book.save();
|
|
1455
|
+
|
|
1456
|
+
// UPDATE `book` SET `title`='Lose Yourself' WHERE `id` = 1;
|
|
1457
|
+
book.title = 'Lose Yourself';
|
|
1458
|
+
await book.save();
|
|
1459
|
+
```
|
|
1460
|
+
- `public static findOne()`
|
|
1461
|
+
Search for a single instance.
|
|
1462
|
+
Returns the first instance found, or null if none can be found.
|
|
1463
|
+
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-findOne) for details.
|
|
1464
|
+
|
|
1465
|
+
**Parameters:**
|
|
1466
|
+
- options: object
|
|
1467
|
+
A hash of options to describe the scope of the search.
|
|
1468
|
+
|
|
1469
|
+
**Return:**
|
|
1470
|
+
`Promise<Model|null>` Returns a Model containing the first data found in the database.
|
|
1471
|
+
|
|
1472
|
+
```js
|
|
1473
|
+
import BookModel from '../models/BookModel';
|
|
1474
|
+
|
|
1475
|
+
// SELECT `id`, `title`, `created`, `modified` FROM `book` AS `book` LIMIT 1;
|
|
1476
|
+
await BookModel.findOne();
|
|
1477
|
+
```
|
|
1478
|
+
- `public static findAll()`
|
|
1479
|
+
Search for multiple instances.
|
|
1480
|
+
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-findAll) for details.
|
|
1481
|
+
|
|
1482
|
+
**Parameters:**
|
|
1483
|
+
- options: object
|
|
1484
|
+
A hash of options to describe the scope of the search.
|
|
1485
|
+
|
|
1486
|
+
**Return:**
|
|
1487
|
+
`Promise<Array<Model>>` Returns a model containing the data found in the database.
|
|
1488
|
+
|
|
1489
|
+
```js
|
|
1490
|
+
import BookModel from '../models/BookModel';
|
|
1491
|
+
|
|
1492
|
+
// SELECT `id`, `title`, `created`, `modified` FROM `book` AS `book` WHERE `book`.`title` LIKE 'Beautiful%';
|
|
1493
|
+
await BookModel.findAll({
|
|
1494
|
+
where: {
|
|
1495
|
+
title: {
|
|
1496
|
+
[BookModel.Op.like]: 'Beautiful%'
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
});
|
|
1500
|
+
```
|
|
1501
|
+
- `public static count()`
|
|
1502
|
+
Count the number of records matching the provided where clause.
|
|
1503
|
+
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-count) for details.
|
|
1504
|
+
|
|
1505
|
+
**Parameters:**
|
|
1506
|
+
- options: object
|
|
1507
|
+
A hash of options to describe the scope of the search.
|
|
1508
|
+
|
|
1509
|
+
**Return:**
|
|
1510
|
+
`Promise<number>` Returns the count of records that match the condition.
|
|
1511
|
+
|
|
1512
|
+
```js
|
|
1513
|
+
import BookModel from '../models/BookModel';
|
|
1514
|
+
|
|
1515
|
+
// SELECT count(*) AS `count` FROM `book` AS `book`;
|
|
1516
|
+
await BookModel.count();
|
|
1517
|
+
```
|
|
1518
|
+
- `public static update()`
|
|
1519
|
+
Update multiple instances that match the where options.
|
|
1520
|
+
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-update) for details.
|
|
1521
|
+
|
|
1522
|
+
**Parameters:**
|
|
1523
|
+
- values: object
|
|
1524
|
+
hash of values to update.
|
|
1525
|
+
- options: object
|
|
1526
|
+
update options.
|
|
1527
|
+
|
|
1528
|
+
**Return:**
|
|
1529
|
+
`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).
|
|
1530
|
+
|
|
1531
|
+
```js
|
|
1532
|
+
import BookModel from '../models/BookModel';
|
|
1533
|
+
|
|
1534
|
+
// UPDATE `book` SET `title`='Lose Yourself' WHERE `id` = 1;
|
|
1535
|
+
await BookModel.update({title: 'Lose Yourself'}, {where: {id: 1}});
|
|
1536
|
+
```
|
|
1537
|
+
- `public static upsert()`
|
|
1538
|
+
Insert or update a single row.
|
|
1539
|
+
An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found.
|
|
1540
|
+
Note that the unique index must be defined in your sequelize model and not just in the table.
|
|
1541
|
+
Otherwise you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.
|
|
1542
|
+
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-upsert) for details.
|
|
1543
|
+
|
|
1544
|
+
**Parameters:**
|
|
1545
|
+
- values: object
|
|
1546
|
+
hash of values to upsert.
|
|
1547
|
+
- options: object
|
|
1548
|
+
upsert options.
|
|
1549
|
+
|
|
1550
|
+
**Return:**
|
|
1551
|
+
`Promise<Model, boolean|null>` returns record and whether row was created or updated as boolean. For Postgres/SQLite dialects boolean value is always null.
|
|
1552
|
+
|
|
1553
|
+
```js
|
|
1554
|
+
import BookModel from '../models/BookModel';
|
|
1555
|
+
|
|
1556
|
+
// INSERT INTO `book` (`title`) VALUES (?) ON DUPLICATE KEY UPDATE `title`=VALUES(`title`);
|
|
1557
|
+
await BookModel.upsert({title: 'Lose Yourself'});
|
|
1558
|
+
```
|
|
1559
|
+
- `public static destroy()`
|
|
1560
|
+
Delete multiple instances, or set their deletedAt timestamp to the current time if paranoid is enabled.
|
|
1561
|
+
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-destroy) for details.
|
|
1562
|
+
|
|
1563
|
+
**Parameters:**
|
|
1564
|
+
- options: object
|
|
1565
|
+
destroy options.
|
|
1566
|
+
|
|
1567
|
+
**Return:**
|
|
1568
|
+
`Promise<number>` The number of destroyed rows.
|
|
1569
|
+
|
|
1570
|
+
```js
|
|
1571
|
+
import BookModel from '../models/BookModel';
|
|
1572
|
+
|
|
1573
|
+
// DELETE FROM `user` WHERE `id` = 1;
|
|
1574
|
+
await BookModel.destroy({where: {id :1}});
|
|
1575
|
+
```
|
|
1576
|
+
- `public static hasOne()`
|
|
1577
|
+
Creates an association between this (the source) and the provided target.
|
|
1578
|
+
The foreign key is added on the target.
|
|
1579
|
+
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-hasOne) for details.
|
|
1580
|
+
|
|
1581
|
+
**Parameters:**
|
|
1582
|
+
- target: Model
|
|
1583
|
+
The target model.
|
|
1584
|
+
- options: object
|
|
1585
|
+
hasOne association options.
|
|
1586
|
+
|
|
1587
|
+
**Return:**
|
|
1588
|
+
[`sequelize.HasOne`](https://sequelize.org/api/v6/class/src/associations/has-one.js~hasone) One-to-one association.
|
|
1589
|
+
|
|
1590
|
+
For one-to-one association we will use two tables as an example they are User and Profile table.
|
|
1591
|
+
User table has one Profile table and Profile table belongs to the User table.
|
|
1592
|
+
Here's the relation diagram for it.
|
|
1593
|
+
|
|
1594
|
+

|
|
1595
|
+
|
|
1596
|
+
HasOne put the association key in the target model.
|
|
1597
|
+
Here User can exist without a Profile, but the vice versa is not possible.
|
|
1598
|
+
This means, we will insert userId field to Profile model’s table.
|
|
1599
|
+
|
|
1600
|
+
This is a user model that defines an association in which the user has one profile.
|
|
1601
|
+
```js
|
|
1602
|
+
import * as expressExtension from 'express-sweet';
|
|
1603
|
+
import ProfileModel from './ProfileModel';
|
|
1604
|
+
|
|
1605
|
+
export default class extends expressExtension.database.Model {
|
|
1606
|
+
static association() {
|
|
1607
|
+
// User has one profile.
|
|
1608
|
+
this.hasOne(ProfileModel, {
|
|
1609
|
+
foreignKey: 'userId', // profile.userId
|
|
1610
|
+
sourceKey: 'id', // user.id
|
|
1611
|
+
as: 'profile'
|
|
1612
|
+
});
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
```
|
|
1616
|
+
|
|
1617
|
+
This is an example of record search.
|
|
1618
|
+
```js
|
|
1619
|
+
import UserModel from '../models/UserModel';
|
|
1620
|
+
|
|
1621
|
+
// SELECT
|
|
1622
|
+
// `user`.`id`,
|
|
1623
|
+
// `user`.`name`,
|
|
1624
|
+
// `profile`.`id` AS `profile.id`,
|
|
1625
|
+
// `profile`.`userId` AS `profile.userId`,
|
|
1626
|
+
// `profile`.`address` AS `profile.address`,
|
|
1627
|
+
// `profile`.`tel` AS `profile.tel`
|
|
1628
|
+
// FROM
|
|
1629
|
+
// `user` AS `user`
|
|
1630
|
+
// LEFT OUTER JOIN `profile` AS `profile` ON `user`.`id` = `profile`.`userId`;
|
|
1631
|
+
//
|
|
1632
|
+
// results in: [
|
|
1633
|
+
// {
|
|
1634
|
+
// "id": 1,
|
|
1635
|
+
// "name": "Robin",
|
|
1636
|
+
// "profile": {
|
|
1637
|
+
// "userId": 1,
|
|
1638
|
+
// "address": "777 Brockton Avenue, Abington MA 2351",
|
|
1639
|
+
// "tel": "202-555-0105"
|
|
1640
|
+
// }
|
|
1641
|
+
// }
|
|
1642
|
+
// ]
|
|
1643
|
+
await UserModel.findAll({
|
|
1644
|
+
attributes: ['id', 'name'],
|
|
1645
|
+
include: [{
|
|
1646
|
+
association: 'profile',
|
|
1647
|
+
attributes: ['userId', 'address', 'tel']
|
|
1648
|
+
}]
|
|
1649
|
+
});
|
|
1650
|
+
```
|
|
1651
|
+
- `public static belongsTo()`
|
|
1652
|
+
Creates an association between this (the source) and the provided target.
|
|
1653
|
+
The foreign key is added on the source.
|
|
1654
|
+
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-belongsTo) for details.
|
|
1655
|
+
|
|
1656
|
+
**Parameters:**
|
|
1657
|
+
- target: Model
|
|
1658
|
+
The target model.
|
|
1659
|
+
- options: object
|
|
1660
|
+
belongsTo association options.
|
|
1661
|
+
|
|
1662
|
+
**Return:**
|
|
1663
|
+
[`sequelize.BelongsTo`](https://sequelize.org/api/v6/class/src/associations/belongs-to.js~belongsto) One-to-one association.
|
|
1664
|
+
|
|
1665
|
+
|
|
1666
|
+
For one-to-one association we will use two tables as an example they are User and Profile table.
|
|
1667
|
+
User table has one Profile table and Profile table belongs to the User table.
|
|
1668
|
+
Here's the relation diagram for it.
|
|
1669
|
+
|
|
1670
|
+

|
|
1671
|
+
|
|
1672
|
+
BelongsTo put the associations key in the source model.
|
|
1673
|
+
Here User can exist without a Profile, but the vice versa is not possible.
|
|
1674
|
+
This means, we will insert userId field to Profile model’s table.
|
|
1675
|
+
|
|
1676
|
+
This is a profile model that defines an association whose profile belongs to one user.
|
|
1677
|
+
```js
|
|
1678
|
+
import * as expressExtension from 'express-sweet';
|
|
1679
|
+
import UserModel from './UserModel';
|
|
1680
|
+
|
|
1681
|
+
export default class extends expressExtension.database.Model {
|
|
1682
|
+
static association() {
|
|
1683
|
+
// Profile belongs to one user.
|
|
1684
|
+
this.belongsTo(UserModel, {
|
|
1685
|
+
foreignKey: 'userId', // profile.userId,
|
|
1686
|
+
targetKey: 'id', // user.id
|
|
1687
|
+
as: 'user'
|
|
1688
|
+
});
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
```
|
|
1692
|
+
|
|
1693
|
+
This is an example of record search.
|
|
1694
|
+
```js
|
|
1695
|
+
import ProfileModel from '../models/ProfileModel';
|
|
1696
|
+
|
|
1697
|
+
// SELECT
|
|
1698
|
+
// `profile`.`id`,
|
|
1699
|
+
// `profile`.`userId`,
|
|
1700
|
+
// `profile`.`address`,
|
|
1701
|
+
// `profile`.`tel`,
|
|
1702
|
+
// `user`.`id` AS `user.id`,
|
|
1703
|
+
// `user`.`name` AS `user.name`
|
|
1704
|
+
// FROM
|
|
1705
|
+
// `profile` AS `profile`
|
|
1706
|
+
// INNER JOIN `user` AS `user` ON `profile`.`userId` = `user`.`id`;
|
|
1707
|
+
//
|
|
1708
|
+
// results in: [
|
|
1709
|
+
// {
|
|
1710
|
+
// "userId": 1,
|
|
1711
|
+
// "address": "777 Brockton Avenue, Abington MA 2351",
|
|
1712
|
+
// "tel": "202-555-0105",
|
|
1713
|
+
// "user": {
|
|
1714
|
+
// "id": 1,
|
|
1715
|
+
// "name": "Robin"
|
|
1716
|
+
// }
|
|
1717
|
+
// }
|
|
1718
|
+
// ]
|
|
1719
|
+
await ProfileModel.findAll({
|
|
1720
|
+
attributes: ['userId', 'address', 'tel'],
|
|
1721
|
+
include: {
|
|
1722
|
+
association: 'user',
|
|
1723
|
+
required: true,
|
|
1724
|
+
attributes: ['id', 'name']
|
|
1725
|
+
}
|
|
1726
|
+
});
|
|
1727
|
+
```
|
|
1728
|
+
- `public static hasMany()`
|
|
1729
|
+
Creates a 1:m association between this (the source) and the provided target.
|
|
1730
|
+
The foreign key is added on the target.
|
|
1731
|
+
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-hasMany) for details.
|
|
1732
|
+
|
|
1733
|
+
**Parameters:**
|
|
1734
|
+
- target: Model
|
|
1735
|
+
The target model.
|
|
1736
|
+
- options: object
|
|
1737
|
+
hasMany association options.
|
|
1738
|
+
|
|
1739
|
+
**Return:**
|
|
1740
|
+
[`sequelize.HasMany`](https://sequelize.org/api/v6/class/src/associations/has-many.js~hasmany) One-to-many association.
|
|
1741
|
+
|
|
1742
|
+
For one-to-many association we will use two tables as an example they are User and Comment table.
|
|
1743
|
+
User table has many Comment table and Comment table belongs to the User table.
|
|
1744
|
+
Here's the relation diagram for it.
|
|
1745
|
+
|
|
1746
|
+

|
|
1747
|
+
|
|
1748
|
+
|
|
1749
|
+
The HasMany put the association key in the target model.
|
|
1750
|
+
Here user and comments share a one to many relationship.
|
|
1751
|
+
Each user can make multiple comments while each comment is associated with only a single user.
|
|
1752
|
+
|
|
1753
|
+
This is a user model that defines an association in which the user has many comments.
|
|
1754
|
+
```js
|
|
1755
|
+
import * as expressExtension from 'express-sweet';
|
|
1756
|
+
import CommentModel from './CommentModel';
|
|
1757
|
+
|
|
1758
|
+
export default class extends expressExtension.database.Model {
|
|
1759
|
+
static association() {
|
|
1760
|
+
// User has many comments.
|
|
1761
|
+
this.hasMany(CommentModel, {
|
|
1762
|
+
foreignKey: 'userId', // comment.userId
|
|
1763
|
+
sourceKey: 'id', // user.id
|
|
1764
|
+
as: 'comments'
|
|
1765
|
+
});
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
```
|
|
1769
|
+
|
|
1770
|
+
This is an example of record search.
|
|
1771
|
+
```js
|
|
1772
|
+
import UserModel from '../models/UserModel';
|
|
1773
|
+
|
|
1774
|
+
// SELECT
|
|
1775
|
+
// `user`.`id`,
|
|
1776
|
+
// `user`.`name`,
|
|
1777
|
+
// `comments`.`id` AS `comments.id`,
|
|
1778
|
+
// `comments`.`userId` AS `comments.userId`,
|
|
1779
|
+
// `comments`.`text` AS `comments.text`
|
|
1780
|
+
// FROM
|
|
1781
|
+
// `user` AS `user`
|
|
1782
|
+
// LEFT OUTER JOIN `comment` AS `comments` ON `user`.`id` = `comments`.`userId`;
|
|
1783
|
+
//
|
|
1784
|
+
// results in: [
|
|
1785
|
+
// {
|
|
1786
|
+
// "id": 1,
|
|
1787
|
+
// "name": "Robin",
|
|
1788
|
+
// "comments": [
|
|
1789
|
+
// {
|
|
1790
|
+
// "userId": 1,
|
|
1791
|
+
// "text": "From Robin #1"
|
|
1792
|
+
// },
|
|
1793
|
+
// {
|
|
1794
|
+
// "userId": 1,
|
|
1795
|
+
// "text": "From Robin #2"
|
|
1796
|
+
// }
|
|
1797
|
+
// ]
|
|
1798
|
+
// }
|
|
1799
|
+
// ]
|
|
1800
|
+
await UserModel.findAll({
|
|
1801
|
+
attributes: ['id', 'name'],
|
|
1802
|
+
include: {
|
|
1803
|
+
association: 'comments',
|
|
1804
|
+
attributes: ['userId', 'text']
|
|
1805
|
+
}
|
|
1806
|
+
});
|
|
1807
|
+
```
|
|
1808
|
+
|
|
1809
|
+
**Using `hasMany` with `findAll`**
|
|
1810
|
+
|
|
1811
|
+
When using `hasMany` association with `findAll` in Sequelize, you need to be aware of the `raw` option's behavior.
|
|
1812
|
+
|
|
1813
|
+
If you want to retrieve child rows as an array within the parent row, you should **disable the `raw` option**.
|
|
1814
|
+
|
|
1815
|
+
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).
|
|
1816
|
+
|
|
1817
|
+
**Example:**
|
|
1818
|
+
|
|
1819
|
+
**With `raw: true`:**
|
|
1820
|
+
|
|
1821
|
+
```json
|
|
1822
|
+
[
|
|
1823
|
+
{
|
|
1824
|
+
"id": 1,
|
|
1825
|
+
"name": "Robin",
|
|
1826
|
+
{
|
|
1827
|
+
"userId": 1,
|
|
1828
|
+
"text": "From Robin #1"
|
|
1829
|
+
}
|
|
1830
|
+
},
|
|
1831
|
+
{
|
|
1832
|
+
"id": 1,
|
|
1833
|
+
"name": "Robin",
|
|
1834
|
+
{
|
|
1835
|
+
"userId": 1,
|
|
1836
|
+
"text": "From Robin #2"
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
]
|
|
1840
|
+
```
|
|
1841
|
+
|
|
1842
|
+
**With `raw: false` (default):**
|
|
1843
|
+
|
|
1844
|
+
```json
|
|
1845
|
+
[
|
|
1846
|
+
{
|
|
1847
|
+
"id": 1,
|
|
1848
|
+
"name": "Robin",
|
|
1849
|
+
"comments": [
|
|
1850
|
+
{
|
|
1851
|
+
"userId": 1,
|
|
1852
|
+
"text": "From Robin #1"
|
|
1853
|
+
},
|
|
1854
|
+
{
|
|
1855
|
+
"userId": 1,
|
|
1856
|
+
"text": "From Robin #2"
|
|
1857
|
+
}
|
|
1858
|
+
]
|
|
1859
|
+
}
|
|
1860
|
+
]
|
|
1861
|
+
```
|
|
1862
|
+
|
|
1863
|
+
- `public static belongsToMany()`
|
|
1864
|
+
Create an N:M association with a join table.
|
|
1865
|
+
Defining through is required.
|
|
1866
|
+
See [here](https://sequelize.org/api/v6/class/src/model.js~model#static-method-belongsToMany) for details.
|
|
1867
|
+
|
|
1868
|
+
**Parameters:**
|
|
1869
|
+
- target: Model
|
|
1870
|
+
The target model.
|
|
1871
|
+
- options: object
|
|
1872
|
+
belongsToMany association options.
|
|
1873
|
+
|
|
1874
|
+
**Return:**
|
|
1875
|
+
[`sequelize.BelongsToMany`](https://sequelize.org/api/v6/class/src/associations/belongs-to-many.js~belongstomany) Many-to-many association with a join table.
|
|
1876
|
+
|
|
1877
|
+
For many-to-many association we will use two tables as an example they are User and Book table.
|
|
1878
|
+
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.
|
|
1879
|
+
Books can belong to many users.
|
|
1880
|
+
Here's the relation diagram for it.
|
|
1881
|
+
|
|
1882
|
+

|
|
1883
|
+
|
|
1884
|
+
The BlongsToMany put the association key in the target model.
|
|
1885
|
+
Here user and book share a many to many relationship.
|
|
1886
|
+
Each user can make multiple books, and each book can be associated with multiple users.
|
|
1887
|
+
|
|
1888
|
+
This is a user model that defines an association where users and books have a many-to-many relationship.
|
|
1889
|
+
```js
|
|
1890
|
+
import * as expressExtension from 'express-sweet';
|
|
1891
|
+
import BookModel from './BookModel';
|
|
1892
|
+
|
|
1893
|
+
export default class extends expressExtension.database.Model {
|
|
1894
|
+
static association() {
|
|
1895
|
+
// Users have many books, and books belong to many users.
|
|
1896
|
+
this.belongsToMany(BookModel, {
|
|
1897
|
+
foreignKey: 'userId', // book.userId
|
|
1898
|
+
sourceKey: 'id', // user.id
|
|
1899
|
+
as: 'books'
|
|
1900
|
+
});
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
```
|
|
1904
|
+
|
|
1905
|
+
This is an example of record search.
|
|
1906
|
+
```js
|
|
1907
|
+
import UserModel from '../models/UserModel';
|
|
1908
|
+
|
|
1909
|
+
// SELECT
|
|
1910
|
+
// `user`.`id`,
|
|
1911
|
+
// `user`.`name`,
|
|
1912
|
+
// `books`.`id` AS `books.id`,
|
|
1913
|
+
// `books`.`userId` AS `books.userId`,
|
|
1914
|
+
// `books`.`title` AS `books.title`
|
|
1915
|
+
// FROM
|
|
1916
|
+
// `user` AS `user`
|
|
1917
|
+
// LEFT OUTER JOIN `book` AS `books` ON `user`.`id` = `books`.`userId`;
|
|
1918
|
+
//
|
|
1919
|
+
// results in: [
|
|
1920
|
+
// {
|
|
1921
|
+
// "id": 1,
|
|
1922
|
+
// "name": "Robin",
|
|
1923
|
+
// "books": [
|
|
1924
|
+
// {
|
|
1925
|
+
// "userId": 1,
|
|
1926
|
+
// "title": "Beautiful"
|
|
1927
|
+
// },
|
|
1928
|
+
// {
|
|
1929
|
+
// "userId": 1,
|
|
1930
|
+
// "title": "Lose Yourself"
|
|
1931
|
+
// }
|
|
1932
|
+
// ]
|
|
1933
|
+
// }
|
|
1934
|
+
// ]
|
|
1935
|
+
await UserModel.findAll({
|
|
1936
|
+
attributes: ['id', 'name'],
|
|
1937
|
+
include: {
|
|
1938
|
+
association: 'books',
|
|
1939
|
+
attributes: ['userId', 'title']
|
|
1940
|
+
}
|
|
1941
|
+
});
|
|
1942
|
+
```
|
|
1943
|
+
- `public static query()`
|
|
1944
|
+
Raw Queries.
|
|
1945
|
+
As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can use the Model.query method.
|
|
1946
|
+
This is an alias for the `sequelize.Sequelize.query()` method.
|
|
1947
|
+
See [here](https://sequelize.org/api/v6/class/src/sequelize.js~sequelize#instance-method-query) for details.
|
|
1948
|
+
|
|
1949
|
+
**Parameters:**
|
|
1950
|
+
- sql: string
|
|
1951
|
+
SQL string.
|
|
1952
|
+
- options: object
|
|
1953
|
+
Query options.
|
|
1954
|
+
|
|
1955
|
+
**Return:**
|
|
1956
|
+
`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.
|
|
1957
|
+
|
|
1958
|
+
```js
|
|
1959
|
+
// By default the function will return two arguments - a results array, and an object containing metadata (such as amount of affected rows, etc).
|
|
1960
|
+
// Note that since this is a raw query, the metadata are dialect specific.
|
|
1961
|
+
const [results, metadata] = await BookModel.query("UPDATE book SET title = 'Lose Yourself' WHERE id = 1");
|
|
1962
|
+
|
|
1963
|
+
// 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:
|
|
1964
|
+
// We didn't need to destructure the result here - the results were returned directly
|
|
1965
|
+
await BookModel.query("SELECT * FROM book", {type: BookModel.QueryTypes.SELECT});
|
|
1966
|
+
```
|
|
1967
|
+
|
|
1968
|
+
### Authentication
|
|
1969
|
+
EXPRESS SWEET has built-in passport authentication middleware for user authentication by username and password.
|
|
1970
|
+
You can immediately start user authentication in your application using the authentication configuration file and the authentication service module.
|
|
1971
|
+
|
|
1972
|
+
For more information about `passport`, click [here](https://www.passportjs.org/).
|
|
1973
|
+
|
|
1974
|
+
**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`.
|
|
1975
|
+
If that access is asynchronous, a `401` error is returned.
|
|
1976
|
+
|
|
1977
|
+
#### Configuration
|
|
1978
|
+
The user authentication configuration is defined in the `config/authentication.js` file.
|
|
1979
|
+
|
|
1980
|
+
Click [here](configuration_sample/esm/authentication.js) to download a sample ESM configuration and
|
|
1981
|
+
[here](configuration_sample/cjs/authentication.js) to download a sample CJS configuration.
|
|
1982
|
+
|
|
1983
|
+
- `enabled: boolean`
|
|
1984
|
+
Set to true to enable user authentication using [Passport middleware](https://www.passportjs.org/docs/).
|
|
1985
|
+
User authentication is enabled (`true`) by default.
|
|
1986
|
+
- `session_store: 'memory'|'redis'`
|
|
1987
|
+
The session store instance, defaults to a new MemoryStore(`memory`) instance.
|
|
1988
|
+
- `cookie_name?: string|undefined`
|
|
1989
|
+
The name of the session ID cookie to set in the response (and read from in the request).
|
|
1990
|
+
The default value is `connect.sid`.
|
|
1991
|
+
- `cookie_secure?: boolean|undefined`
|
|
1992
|
+
Specifies the boolean value for the `Secure` Set-Cookie attribute.
|
|
1993
|
+
The default is `true`, which sets the `Secure` attribute on the cookie.
|
|
1994
|
+
- `cookie_httpOnly?: boolean|undefined`
|
|
1995
|
+
Specifies the boolean value for the `HttpOnly` Set-Cookie attribute.
|
|
1996
|
+
Defaults to `true`, which sets the `HttpOnly` attribute on the cookie.
|
|
1997
|
+
- `redis_host?: string|undefined`
|
|
1998
|
+
If the session is stored in `redis`, this field is required and should be set to the hostname of the Redis server.
|
|
1999
|
+
For example, to connect to redis on localhost on port `6379`, set `redis://localhost:6379`.
|
|
2000
|
+
|
|
2001
|
+
To connect to a different host or port, use a connection string in the format `redis[s]://[[username][:password]@][host][:port][/db-number]`.
|
|
2002
|
+
For example, `redis://alice:foobared@awesome.redis.server:6380`.
|
|
2003
|
+
- `username: string`
|
|
2004
|
+
The login username field name used for authentication.
|
|
2005
|
+
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.
|
|
2006
|
+
- `password: string`
|
|
2007
|
+
The login password field name used for authentication.
|
|
2008
|
+
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.
|
|
2009
|
+
- `success_redirect: string`
|
|
2010
|
+
The URL to redirect to after successful authentication.
|
|
2011
|
+
The default is the root URL (`/`).
|
|
2012
|
+
- `failure_redirect: string|((req: express.Request, res: express.Response) => string)`
|
|
2013
|
+
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.
|
|
2014
|
+
This usually specifies the URL of the login page.
|
|
2015
|
+
The default is `/login`.
|
|
2016
|
+
```js
|
|
2017
|
+
// Set the URL to redirect to in case of login failure as a string.
|
|
2018
|
+
failure_redirect: '/login',
|
|
2019
|
+
|
|
2020
|
+
// Dynamically set the url to redirect to on login failure.
|
|
2021
|
+
failure_redirect: (req, res) => {
|
|
2022
|
+
// If the role stored in the cookie is admin, redirect to the admin login screen.
|
|
2023
|
+
return req.cookies.role === 'admin' ? '/adminlogin' : 'login';
|
|
2024
|
+
},
|
|
2025
|
+
```
|
|
2026
|
+
- `authenticate_user: (username: string, password: string, req: express.Request): Promise<object|null>`
|
|
2027
|
+
This hook is called when authenticating a user.
|
|
2028
|
+
Please find the user information that owns the credentials based on the user name and password you received and return it.
|
|
2029
|
+
If the user who owns the credentials cannot be found, return null.
|
|
2030
|
+
|
|
2031
|
+
**NOTE:** Note that the user information must include an ID value that can identify the user.
|
|
2032
|
+
|
|
2033
|
+
The following example uses the user model to find the user who owns the credentials based on the username and password.
|
|
2034
|
+
```js
|
|
2035
|
+
authenticate_user: async (username, password, req) => {
|
|
2036
|
+
const UserModel = require('../models/UserModel');
|
|
2037
|
+
return UserModel.findOne({
|
|
2038
|
+
where: {
|
|
2039
|
+
email: username,
|
|
2040
|
+
password
|
|
2041
|
+
},
|
|
2042
|
+
raw: true
|
|
2043
|
+
});
|
|
2044
|
+
}
|
|
2045
|
+
```
|
|
2046
|
+
- `subscribe_user: (id: number): Promise<object>`
|
|
2047
|
+
This hook is called when user authentication is successful.
|
|
2048
|
+
Please search and return the authenticated user information to be set in the session based on the user ID of the parameter.
|
|
2049
|
+
The returned data will be set in the req.user property and the view's session variable.
|
|
2050
|
+
The following example uses the user model to return the user information that owns the credentials based on the authenticated user's id.
|
|
2051
|
+
```js
|
|
2052
|
+
subscribe_user: async (id) => {
|
|
2053
|
+
const UserModel = require('../models/UserModel');
|
|
2054
|
+
return UserModel.findOne({
|
|
2055
|
+
where: {
|
|
2056
|
+
id
|
|
2057
|
+
},
|
|
2058
|
+
raw: true
|
|
2059
|
+
});
|
|
2060
|
+
}
|
|
2061
|
+
```
|
|
2062
|
+
- `allow_unauthenticated: (string|RegExp)[]`
|
|
2063
|
+
By default, it requires an authenticated user for all requests.
|
|
2064
|
+
You can use the `allow_unauthenticated` option to disable this behavior on certain requests.
|
|
2065
|
+
For example, if you don’t want to authenticate all requests that contain `api` in the URL, set `allow_unauthenticated` as follows.
|
|
2066
|
+
```js
|
|
2067
|
+
allow_unauthenticated: ['/api']
|
|
2068
|
+
```
|
|
2069
|
+
|
|
2070
|
+
You can also use regular expressions.
|
|
2071
|
+
```js
|
|
2072
|
+
allow_unauthenticated: [/^\/api/]
|
|
2073
|
+
```
|
|
2074
|
+
- `expiration: number`
|
|
2075
|
+
Specifies the time, in milliseconds, before the session expires.
|
|
2076
|
+
The default is 24 hours (`86400000` milliseconds).
|
|
2077
|
+
|
|
2078
|
+
#### Login Procedure
|
|
2079
|
+
To authenticate the request, call `services/Authentication.authenticate()` method.
|
|
2080
|
+
This method returns `true` if the authentication succeeds and `false` if it fails.
|
|
2081
|
+
If authentication succeeds, the next handler will be invoked and the `req.user` property will be set to the authenticated user.
|
|
2082
|
+
|
|
2083
|
+
The post-authentication logic depends on whether the login request is received asynchronously or synchronously, so an example of both logics is shown here.
|
|
2084
|
+
|
|
2085
|
+
1. Create a user table to authenticate.
|
|
2086
|
+
```sql
|
|
2087
|
+
CREATE TABLE `user` (
|
|
2088
|
+
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
|
|
2089
|
+
`name` varchar(30) NOT NULL,
|
|
2090
|
+
`email` varchar(255) NOT NULL,
|
|
2091
|
+
`password` varchar(100) NOT NULL,
|
|
2092
|
+
`icon` varchar(768) NOT NULL DEFAULT MD5(RAND()),
|
|
2093
|
+
`created` datetime NOT NULL DEFAULT current_timestamp(),
|
|
2094
|
+
`modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
|
|
2095
|
+
PRIMARY KEY (`id`),
|
|
2096
|
+
UNIQUE KEY `ukUserEmail` (`email`),
|
|
2097
|
+
UNIQUE KEY `ukUserIcon`(`icon`)
|
|
2098
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
|
2099
|
+
```
|
|
2100
|
+
1. Set the email address and password columns of the user table to be used for authentication in the config file `config/authentication.js`.
|
|
2101
|
+
```js
|
|
2102
|
+
/**
|
|
2103
|
+
* Authentication user ID field name, defaults to `username`.
|
|
2104
|
+
* @type {string}
|
|
2105
|
+
*/
|
|
2106
|
+
username: 'email',
|
|
2107
|
+
|
|
2108
|
+
/**
|
|
2109
|
+
* Authentication password field name, defaults to `password`.
|
|
2110
|
+
* @type {string}
|
|
2111
|
+
*/
|
|
2112
|
+
password: 'password'
|
|
2113
|
+
```
|
|
2114
|
+
1. For asynchronous requests.
|
|
2115
|
+
Returns the authentication result and executes subsequent processing on the front end.
|
|
2116
|
+
|
|
2117
|
+
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.
|
|
2118
|
+
After that, the front end checks the authentication result returned from the router and redirects to `/` if the authentication result is successful (`true`).
|
|
2119
|
+
If you redirect to /, the page will automatically switch to the URL specified in `success_redirect` of `config/authentication.js`.
|
|
2120
|
+
```js
|
|
2121
|
+
import {Router} from 'express';
|
|
2122
|
+
import * as expressExtension from 'express-sweet';
|
|
2123
|
+
|
|
2124
|
+
const router = Router();
|
|
2125
|
+
router.post('/login', async (req, res, next) => {
|
|
2126
|
+
const isAuthenticated = await expressExtension.services.Authentication.authenticate(req, res, next);
|
|
2127
|
+
res.json(isAuthenticated);
|
|
2128
|
+
});
|
|
2129
|
+
export default router;
|
|
2130
|
+
```
|
|
2131
|
+
|
|
2132
|
+
Below is an example of HTML.
|
|
2133
|
+
```html
|
|
2134
|
+
<form id="form">
|
|
2135
|
+
<label>Email</label><input type="email" name="email" required autofocus>
|
|
2136
|
+
<label class="form-label">Password</label><input type="password" name="password" required>
|
|
2137
|
+
<button type="submit">Login</button>
|
|
2138
|
+
</form>
|
|
2139
|
+
<script>
|
|
2140
|
+
const form = document.querySelector('#form');
|
|
2141
|
+
form.addEventListener('submit', async event => {
|
|
2142
|
+
event.preventDefault();
|
|
2143
|
+
const res = await fetch('/api/users/login', {method: 'POST', body: new FormData(form)});
|
|
2144
|
+
const isAuthenticated = await res.json();
|
|
2145
|
+
if (!isAuthenticated)
|
|
2146
|
+
return void alert('The user name or password is incorrect.');
|
|
2147
|
+
location.href = '/';
|
|
2148
|
+
});
|
|
2149
|
+
</script>
|
|
2150
|
+
```
|
|
2151
|
+
1. For sync request.
|
|
2152
|
+
If the authentication is successful, redirect to the page with the URL specified by `success_redirect` in `config/authentication.js`.
|
|
2153
|
+
If it fails, redirect to the page with the URL specified by `failure_redirect` in `config/authentication.js`.
|
|
2154
|
+
```js
|
|
2155
|
+
import {Router} from 'express';
|
|
2156
|
+
import * as expressExtension from 'express-sweet';
|
|
2157
|
+
|
|
2158
|
+
const router = Router();
|
|
2159
|
+
router.post('/login', async (req, res, next) => {
|
|
2160
|
+
const isAuthenticated = await expressExtension.services.Authentication.authenticate(req, res, next);
|
|
2161
|
+
if (isAuthenticated)
|
|
2162
|
+
await expressExtension.services.Authentication.successRedirect(res);
|
|
2163
|
+
else
|
|
2164
|
+
await expressExtension.services.Authentication.failureRedirect(req, res);
|
|
2165
|
+
});
|
|
2166
|
+
export default router;
|
|
2167
|
+
```
|
|
2168
|
+
|
|
2169
|
+
Below is an example of HTML.
|
|
2170
|
+
```html
|
|
2171
|
+
<form method="post" action="/api/users/login">
|
|
2172
|
+
<label>Email</label><input type="email" name="email" required autofocus>
|
|
2173
|
+
<label class="form-label">Password</label><input type="password" name="password" required>
|
|
2174
|
+
<button type="submit">Login</button>
|
|
2175
|
+
</form>
|
|
2176
|
+
```
|
|
2177
|
+
|
|
2178
|
+
#### Logout Procedure
|
|
2179
|
+
If you want to log out the user, call the `services/Authentication.logout()` method.
|
|
2180
|
+
Invoking `logout()` will remove the `req.user` property and clear the login session (if any).
|
|
2181
|
+
```js
|
|
2182
|
+
import {Router} from 'express';
|
|
2183
|
+
import * as expressExtension from 'express-sweet';
|
|
2184
|
+
|
|
2185
|
+
const router = Router();
|
|
2186
|
+
router.get('/logout', (req, res) => {
|
|
2187
|
+
expressExtension.services.Authentication.logout(req);
|
|
2188
|
+
res.redirect('/');
|
|
2189
|
+
});
|
|
2190
|
+
export default router;
|
|
2191
|
+
```
|
|
2192
|
+
|
|
2193
|
+
Below is an example of HTML.
|
|
2194
|
+
```html
|
|
2195
|
+
<a href="/api/users/logout">Logout</a>
|
|
2196
|
+
```
|
|
13
2197
|
|
|
14
2198
|
## Release Notes
|
|
15
2199
|
All changes can be found [here](CHANGELOG.md).
|
|
16
2200
|
|
|
17
|
-
- ### [2.0.2] - 2024/9/1
|
|
18
|
-
#### Changed
|
|
19
|
-
- Update express from 4.18.3 to 4.19.2.
|
|
20
|
-
- Update rollup from 2.79.1 to 4.21.2.
|
|
21
|
-
- Rename build files (build.common.js => build.cjs, build.esm.js => build.mjs).
|
|
22
|
-
- The express package was excluded from the build file. Instead, users should install express on their own.
|
|
23
|
-
- ### [2.0.1] - 2024/4/5
|
|
24
|
-
#### Changed
|
|
25
|
-
- Removed [nodejs-shared](https://www.npmjs.com/package/nodejs-shared) package dependency.
|
|
26
|
-
The `services.AWSRekognitionClient` and `services.AWSSesClient` have been migrated to the [AWS SDK Extension](https://www.npmjs.com/package/aws-sdk-extension) NPM package, so please install from there if needed.
|
|
27
|
-
|
|
28
2201
|
## Author
|
|
29
2202
|
**Takuya Motoshima**
|
|
30
2203
|
|