express-sweet-generator 2.0.7 → 2.0.9

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/README.md CHANGED
@@ -145,6 +145,8 @@ Use the application generator tool, `express-sweet-generator`, to quickly create
145
145
  │ └── view.js
146
146
  ├── errors
147
147
  │ └── NotFoundError.js
148
+ ├── middlewares
149
+ │ └── checkValidationResult.js
148
150
  ├── models
149
151
  │ ├── BookModel.js
150
152
  │ ├── CommentModel.js
@@ -159,8 +161,9 @@ Use the application generator tool, `express-sweet-generator`, to quickly create
159
161
  │ └── api
160
162
  │ └── users.js
161
163
  ├── shared
162
- │ ├── CustomValidation.js
163
- │ └── empty.js
164
+ │ └── isEmpty.js
165
+ ├── validators
166
+ │ └── isValidImageDataUrl.js
164
167
  └── views
165
168
  ├── edit-personal.hbs
166
169
  ├── error.hbs
@@ -170,7 +173,10 @@ Use the application generator tool, `express-sweet-generator`, to quickly create
170
173
  ├── layout
171
174
  │ └── default.hbs
172
175
  └── partials
173
- └── .gitkeep
176
+ │ └── .gitkeep
177
+ └── errors
178
+ ├── 404.hbs
179
+ └── 500.hbs
174
180
  ```
175
181
 
176
182
  ## Author
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-sweet-generator",
3
- "version": "2.0.7",
3
+ "version": "2.0.9",
4
4
  "description": "EXPRESS SWEET application generator.",
5
5
  "main": "bin/express-sweet-cli.js",
6
6
  "files": [
@@ -1 +1,2 @@
1
- NODE_ENV=development
1
+ NODE_ENV=development
2
+ LOG_VALIDATION_ERRORS=true
@@ -4,7 +4,7 @@
4
4
  module.exports = class extends Error {
5
5
  /**
6
6
  * Creates a new NotFoundError instance.
7
- * @param {string} [message='The requested record could not be found.'] - The error message.
7
+ * @param {string} [message='The requested record could not be found.'] The error message.
8
8
  */
9
9
  constructor(message = 'The requested record could not be found.') {
10
10
  super(message);
@@ -0,0 +1,16 @@
1
+ const {validationResult} = require('express-validator');
2
+
3
+ /**
4
+ * Check express-validator results. Returns 400 HTTP status if parameter is invalid.
5
+ */
6
+ module.exports = (req, res, next) => {
7
+ const result = validationResult(req);
8
+ if (result.isEmpty())
9
+ next();
10
+ else {
11
+ // Log validation errors only if LOG_VALIDATION_ERRORS is enabled
12
+ if (process.env.LOG_VALIDATION_ERRORS === 'true')
13
+ console.error('Validation errors:', result.array());
14
+ res.status(400).end();
15
+ }
16
+ }
@@ -67,19 +67,21 @@ module.exports = class extends expressExtension.database.Model {
67
67
  dir: 'asc',
68
68
  search: null,
69
69
  }, options);
70
+
70
71
  const recordsTotal = await super.count();
71
- let where;
72
+
73
+ const whereClause = {};
72
74
  if (options.search)
73
- where = {
74
- [super.Op.or]: [
75
- {email: {[super.Op.like]: `%${options.search}%`}},
76
- {name: {[super.Op.like]: `%${options.search}%`}}
77
- ]
78
- };
79
- const recordsFiltered = await super.count({where});
75
+ whereClause[super.Op.or] = [
76
+ {email: {[super.Op.like]: `%${options.search}%`}},
77
+ {name: {[super.Op.like]: `%${options.search}%`}}
78
+ ];
79
+
80
+ const recordsFiltered = await super.count({where: whereClause});
81
+
80
82
  const data = await super.findAll({
81
83
  attributes: ['id', 'name', 'email', 'icon', 'modified'],
82
- where,
84
+ where: whereClause,
83
85
  order: [[options.order, options.dir]],
84
86
  offset: parseInt(options.start, 10),
85
87
  limit: parseInt(options.length),
@@ -88,23 +90,27 @@ module.exports = class extends expressExtension.database.Model {
88
90
  return {recordsTotal, recordsFiltered, data};
89
91
  }
90
92
 
91
- static async createUser(set) {
93
+ static async createUser(userData) {
92
94
  let transaction;
93
95
  try {
94
- set = Object.assign({
96
+ userData = Object.assign({
95
97
  email: null,
96
98
  name: null,
97
99
  password: null,
98
100
  icon: null
99
- }, set);
101
+ }, userData);
100
102
  transaction = await super.begin();
101
103
  const user = await super.create({
102
- name: set.name,
103
- email: set.email,
104
- password: set.password,
104
+ name: userData.name,
105
+ email: userData.email,
106
+ password: userData.password,
105
107
  }, {transaction});
106
- await this.#updateUserIcon(user, set.icon, transaction);
108
+
109
+ await this.#updateUserIcon(user, userData.icon, transaction);
110
+
107
111
  await transaction.commit();
112
+
113
+ console.log('Successfully created a new user with ID:', user.id);
108
114
  } catch (error) {
109
115
  if (transaction)
110
116
  await transaction.rollback();
@@ -112,27 +118,31 @@ module.exports = class extends expressExtension.database.Model {
112
118
  }
113
119
  }
114
120
 
115
- static async updateUser(userId, set) {
121
+ static async updateUser(userId, userData) {
116
122
  let transaction;
117
123
  try {
118
- set = Object.assign({
124
+ userData = Object.assign({
119
125
  email: null,
120
126
  name: null,
121
127
  password: null,
122
128
  icon: null
123
- }, set);
129
+ }, userData);
124
130
  const user = await this.getUser(userId);
125
131
  if (!user)
126
132
  throw new NotFoundError();
127
133
  transaction = await super.begin();
128
- user.email = set.email;
129
- user.name = set.name;
134
+ user.email = userData.email;
135
+ user.name = userData.name;
130
136
  user.modified = super.literal('CURRENT_TIMESTAMP');
131
- if (set.password)
132
- user.password = set.password;
137
+ if (userData.password)
138
+ user.password = userData.password;
139
+
133
140
  await user.save({transaction});
134
- await this.#updateUserIcon(user, set.icon, transaction);
141
+ await this.#updateUserIcon(user, userData.icon, transaction);
142
+
135
143
  await transaction.commit();
144
+
145
+ console.log(`Successfully updated user with ID: ${userId}`);
136
146
  } catch (error) {
137
147
  if (transaction)
138
148
  await transaction.rollback();
@@ -144,26 +154,25 @@ module.exports = class extends expressExtension.database.Model {
144
154
  user.icon = `/upload/${user.id}.${Media.getExtensionFromDataUrl(dataUrl)}`;
145
155
  await user.save({transaction});
146
156
  const iconPath = `${global.APP_DIR}/public${user.icon}`;
147
- console.log(`Write ${iconPath}`);
148
157
  Media.writeDataUrlToFile(iconPath, dataUrl);
149
158
  }
150
159
 
151
160
  static async deleteUser(userId) {
152
- console.log(`Delete a user whose ID is ${userId}`);
153
- return super.destroy({where: {id: userId}});
161
+ await super.destroy({where: {id: userId}});
162
+ console.log(`Successfully deleted user with ID: ${userId}`);
154
163
  }
155
164
 
156
165
  static async emailExists(email, excludeUserId = null) {
157
- const where = {email};
166
+ const whereClause = {email};
158
167
  if (excludeUserId)
159
- where.id = {[super.Op.ne]: excludeUserId};
160
- return await super.count({where}) > 0;
168
+ whereClause.id = {[super.Op.ne]: excludeUserId};
169
+ return await super.count({where: whereClause}) > 0;
161
170
  }
162
171
 
163
172
  static async userIdExists(userId) {
164
- const where = {email};
173
+ const whereClause = {email};
165
174
  if (excludeUserId)
166
- where.id = {[super.Op.ne]: excludeUserId};
167
- return await super.count({where}) > 0;
175
+ whereClause.id = {[super.Op.ne]: excludeUserId};
176
+ return await super.count({where: whereClause}) > 0;
168
177
  }
169
178
  }
@@ -1,19 +1,18 @@
1
1
  const express = require('express');
2
2
  const expressExtension = require('express-sweet');
3
- const {query, body, validationResult} = require('express-validator');
3
+ const {query, body} = require('express-validator');
4
4
  const UserModel = require('../../models/UserModel');
5
5
  const NotFoundError = require('../../errors/NotFoundError');
6
- const CustomValidation = require('../../shared/CustomValidation');
6
+ const isValidImageDataUrl = require('../../validators/isValidImageDataUrl');
7
+ const checkValidationResult = require('../../middlewares/checkValidationResult');
7
8
 
8
9
  const router = express.Router();
9
10
 
10
11
  router.post('/login', [
11
12
  body('email').trim().not().isEmpty().isEmail(),
12
- body('password').trim().not().isEmpty()
13
+ body('password').trim().not().isEmpty(),
14
+ checkValidationResult,
13
15
  ], async (req, res, next) => {
14
- const result = validationResult(req);
15
- if (!result.isEmpty())
16
- return void res.status(400).json({errors: result.array()});
17
16
  const isAuthenticated = await expressExtension.services.Authentication.authenticate(req, res, next);
18
17
  res.json(isAuthenticated);
19
18
  });
@@ -29,11 +28,9 @@ router.get('/', [
29
28
  query('length').not().isEmpty().isInt({min: 1}),
30
29
  query('order').not().isEmpty().isIn(['name', 'email', 'modified']),
31
30
  query('dir').optional({nullable: true, checkFalsy: true}).isIn(['asc', 'desc']),
32
- query('search').trim().optional({nullable: true, checkFalsy: true}).trim()
31
+ query('search').trim().optional({nullable: true, checkFalsy: true}).trim(),
32
+ checkValidationResult,
33
33
  ], async (req, res) => {
34
- const result = validationResult(req);
35
- if (!result.isEmpty())
36
- return void res.status(400).json({errors: result.array()});
37
34
  const data = await UserModel.paginate(req.query);
38
35
  data.draw = req.query.draw;
39
36
  res.json(data);
@@ -41,11 +38,9 @@ router.get('/', [
41
38
 
42
39
  router.get('/email-exists', [
43
40
  query('user.email').trim().not().isEmpty(),
44
- query('excludeUserId').optional({nullable: true, checkFalsy: true}).isInt({min: 1})
41
+ query('excludeUserId').optional({nullable: true, checkFalsy: true}).isInt({min: 1}),
42
+ checkValidationResult,
45
43
  ], async (req, res) => {
46
- const result = validationResult(req);
47
- if (!result.isEmpty())
48
- return void res.status(400).json({errors: result.array()});
49
44
  const emailExists = await UserModel.emailExists(req.query.user.email, req.query.excludeUserId || null);
50
45
  res.json({valid: !emailExists});
51
46
  });
@@ -54,11 +49,9 @@ router.post('/', [
54
49
  body('user.email').trim().not().isEmpty().isEmail(),
55
50
  body('user.name').trim().not().isEmpty().isLength({max: 30}),
56
51
  body('user.password').trim().not().isEmpty().isLength({max: 128}),
57
- body('user.icon').not().isEmpty().custom(CustomValidation.isImageDataUrl)
52
+ body('user.icon').not().isEmpty().custom(isValidImageDataUrl),
53
+ checkValidationResult,
58
54
  ], async (req, res) => {
59
- const result = validationResult(req);
60
- if (!result.isEmpty())
61
- return void res.status(400).json({errors: result.array()});
62
55
  await UserModel.createUser(req.body.user);
63
56
  res.json(true);
64
57
  });
@@ -72,12 +65,10 @@ router.put('/:userId(\\d+)', [
72
65
  body('user.email').trim().not().isEmpty().isEmail(),
73
66
  body('user.name').trim().not().isEmpty().isLength({max: 30}),
74
67
  body('user.password').trim().optional({nullable: true, checkFalsy: true}).isLength({max: 128}),
75
- body('user.icon').not().isEmpty().custom(CustomValidation.isImageDataUrl)
68
+ body('user.icon').not().isEmpty().custom(isValidImageDataUrl),
69
+ checkValidationResult,
76
70
  ], async (req, res, next) => {
77
71
  try {
78
- const result = validationResult(req);
79
- if (!result.isEmpty())
80
- return void res.status(400).json({errors: result.array()});
81
72
  await UserModel.updateUser(req.params.userId, req.body.user);
82
73
  res.json(true);
83
74
  } catch (error) {
@@ -97,12 +88,10 @@ router.put('/profile', [
97
88
  body('user.email').trim().not().isEmpty().isEmail(),
98
89
  body('user.name').trim().not().isEmpty().isLength({max: 30}),
99
90
  body('user.password').trim().optional({nullable: true, checkFalsy: true}).isLength({max: 128}),
100
- body('user.icon').not().isEmpty().custom(CustomValidation.isImageDataUrl)
91
+ body('user.icon').not().isEmpty().custom(isValidImageDataUrl),
92
+ checkValidationResult,
101
93
  ], async (req, res, next) => {
102
94
  try {
103
- const result = validationResult(req);
104
- if (!result.isEmpty())
105
- return void res.status(400).json({errors: result.array()});
106
95
  await UserModel.updateUser(req.user.id, req.body.user);
107
96
  res.json(true);
108
97
  } catch (error) {
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Checks if a string is empty or contains only whitespace characters.
3
+ * @param {string|null|false} str The string to check.
4
+ * @return {boolean} True if the string is empty or contains only whitespace, false otherwise.
5
+ */
6
+ module.exports = str => {
7
+ if (str == null || str === false)
8
+ return true;
9
+ return str.toString().trim() === '';
10
+ }
@@ -0,0 +1,16 @@
1
+ const isEmpty = require('../shared/isEmpty');
2
+
3
+ /**
4
+ * Validates if a value is a valid image Data URL.
5
+ * @param {string} value The value to validate.
6
+ * @return {boolean} True if the value is a valid image Data URL or empty, otherwise throws an error.
7
+ * @throws {Error} If the value is not a valid image Data URL format.
8
+ */
9
+ module.exports = (value) => {
10
+ if (isEmpty(value))
11
+ return true; // Empty values are considered valid
12
+ const dataUrlRegex = /^data:image\/[\w-+\d.]+;\w+,/;
13
+ if (!dataUrlRegex.test(value))
14
+ throw new Error('Invalid image Data URL format.');
15
+ return true;
16
+ }
@@ -1 +1,2 @@
1
- NODE_ENV=development
1
+ NODE_ENV=development
2
+ LOG_VALIDATION_ERRORS=true
@@ -4,7 +4,7 @@
4
4
  export default class extends Error {
5
5
  /**
6
6
  * Creates a new NotFoundError instance.
7
- * @param {string} [message='The requested record could not be found.'] - The error message.
7
+ * @param {string} [message='The requested record could not be found.'] The error message.
8
8
  */
9
9
  constructor(message = 'The requested record could not be found.') {
10
10
  super(message);
@@ -0,0 +1,16 @@
1
+ import {validationResult} from 'express-validator';
2
+
3
+ /**
4
+ * Check express-validator results. Returns 400 HTTP status if parameter is invalid.
5
+ */
6
+ export default (req, res, next) => {
7
+ const result = validationResult(req);
8
+ if (result.isEmpty())
9
+ next();
10
+ else {
11
+ // Log validation errors only if LOG_VALIDATION_ERRORS is enabled
12
+ if (process.env.LOG_VALIDATION_ERRORS === 'true')
13
+ console.error('Validation errors:', result.array());
14
+ res.status(400).end();
15
+ }
16
+ }
@@ -67,19 +67,21 @@ export default class extends expressExtension.database.Model {
67
67
  dir: 'asc',
68
68
  search: null,
69
69
  }, options);
70
+
70
71
  const recordsTotal = await super.count();
71
- let where;
72
+
73
+ const whereClause = {};
72
74
  if (options.search)
73
- where = {
74
- [super.Op.or]: [
75
- {email: {[super.Op.like]: `%${options.search}%`}},
76
- {name: {[super.Op.like]: `%${options.search}%`}}
77
- ]
78
- };
79
- const recordsFiltered = await super.count({where});
75
+ whereClause[super.Op.or] = [
76
+ {email: {[super.Op.like]: `%${options.search}%`}},
77
+ {name: {[super.Op.like]: `%${options.search}%`}}
78
+ ];
79
+
80
+ const recordsFiltered = await super.count({where: whereClause});
81
+
80
82
  const data = await super.findAll({
81
83
  attributes: ['id', 'name', 'email', 'icon', 'modified'],
82
- where,
84
+ where: whereClause,
83
85
  order: [[options.order, options.dir]],
84
86
  offset: parseInt(options.start, 10),
85
87
  limit: parseInt(options.length),
@@ -88,23 +90,27 @@ export default class extends expressExtension.database.Model {
88
90
  return {recordsTotal, recordsFiltered, data};
89
91
  }
90
92
 
91
- static async createUser(set) {
93
+ static async createUser(userData) {
92
94
  let transaction;
93
95
  try {
94
- set = Object.assign({
96
+ userData = Object.assign({
95
97
  email: null,
96
98
  name: null,
97
99
  password: null,
98
100
  icon: null
99
- }, set);
101
+ }, userData);
100
102
  transaction = await super.begin();
101
103
  const user = await super.create({
102
- name: set.name,
103
- email: set.email,
104
- password: set.password,
104
+ name: userData.name,
105
+ email: userData.email,
106
+ password: userData.password,
105
107
  }, {transaction});
106
- await this.#updateUserIcon(user, set.icon, transaction);
108
+
109
+ await this.#updateUserIcon(user, userData.icon, transaction);
110
+
107
111
  await transaction.commit();
112
+
113
+ console.log('Successfully created a new user with ID:', user.id);
108
114
  } catch (error) {
109
115
  if (transaction)
110
116
  await transaction.rollback();
@@ -112,27 +118,31 @@ export default class extends expressExtension.database.Model {
112
118
  }
113
119
  }
114
120
 
115
- static async updateUser(userId, set) {
121
+ static async updateUser(userId, userData) {
116
122
  let transaction;
117
123
  try {
118
- set = Object.assign({
124
+ userData = Object.assign({
119
125
  email: null,
120
126
  name: null,
121
127
  password: null,
122
128
  icon: null
123
- }, set);
129
+ }, userData);
124
130
  const user = await this.getUser(userId);
125
131
  if (!user)
126
132
  throw new NotFoundError();
127
133
  transaction = await super.begin();
128
- user.email = set.email;
129
- user.name = set.name;
134
+ user.email = userData.email;
135
+ user.name = userData.name;
130
136
  user.modified = super.literal('CURRENT_TIMESTAMP');
131
- if (set.password)
132
- user.password = set.password;
137
+ if (userData.password)
138
+ user.password = userData.password;
139
+
133
140
  await user.save({transaction});
134
- await this.#updateUserIcon(user, set.icon, transaction);
141
+ await this.#updateUserIcon(user, userData.icon, transaction);
142
+
135
143
  await transaction.commit();
144
+
145
+ console.log(`Successfully updated user with ID: ${userId}`);
136
146
  } catch (error) {
137
147
  if (transaction)
138
148
  await transaction.rollback();
@@ -144,26 +154,25 @@ export default class extends expressExtension.database.Model {
144
154
  user.icon = `/upload/${user.id}.${Media.getExtensionFromDataUrl(dataUrl)}`;
145
155
  await user.save({transaction});
146
156
  const iconPath = `${global.APP_DIR}/public${user.icon}`;
147
- console.log(`Write ${iconPath}`);
148
157
  Media.writeDataUrlToFile(iconPath, dataUrl);
149
158
  }
150
159
 
151
160
  static async deleteUser(userId) {
152
- console.log(`Delete a user whose ID is ${userId}`);
153
- return super.destroy({where: {id: userId}});
161
+ await super.destroy({where: {id: userId}});
162
+ console.log(`Successfully deleted user with ID: ${userId}`);
154
163
  }
155
164
 
156
165
  static async emailExists(email, excludeUserId = null) {
157
- const where = {email};
166
+ const whereClause = {email};
158
167
  if (excludeUserId)
159
- where.id = {[super.Op.ne]: excludeUserId};
160
- return await super.count({where}) > 0;
168
+ whereClause.id = {[super.Op.ne]: excludeUserId};
169
+ return await super.count({where: whereClause}) > 0;
161
170
  }
162
171
 
163
172
  static async userIdExists(userId) {
164
- const where = {email};
173
+ const whereClause = {email};
165
174
  if (excludeUserId)
166
- where.id = {[super.Op.ne]: excludeUserId};
167
- return await super.count({where}) > 0;
175
+ whereClause.id = {[super.Op.ne]: excludeUserId};
176
+ return await super.count({where: whereClause}) > 0;
168
177
  }
169
178
  }
@@ -1,19 +1,18 @@
1
1
  import * as expressExtension from 'express-sweet';
2
2
  import {Router} from 'express';
3
- import {query, body, validationResult} from 'express-validator';
3
+ import {query, body} from 'express-validator';
4
4
  import UserModel from '../../models/UserModel.js';
5
5
  import NotFoundError from '../../errors/NotFoundError.js';
6
- import * as CustomValidation from '../../shared/CustomValidation.js';
6
+ import isValidImageDataUrl from '../../validators/isValidImageDataUrl.js';
7
+ import checkValidationResult from '../../middlewares/checkValidationResult.js';
7
8
 
8
9
  const router = Router();
9
10
 
10
11
  router.post('/login', [
11
12
  body('email').trim().not().isEmpty().isEmail(),
12
- body('password').trim().not().isEmpty()
13
+ body('password').trim().not().isEmpty(),
14
+ checkValidationResult,
13
15
  ], async (req, res, next) => {
14
- const result = validationResult(req);
15
- if (!result.isEmpty())
16
- return void res.status(400).json({errors: result.array()});
17
16
  const isAuthenticated = await expressExtension.services.Authentication.authenticate(req, res, next);
18
17
  res.json(isAuthenticated);
19
18
  });
@@ -29,11 +28,9 @@ router.get('/', [
29
28
  query('length').not().isEmpty().isInt({min: 1}),
30
29
  query('order').not().isEmpty().isIn(['name', 'email', 'modified']),
31
30
  query('dir').optional({nullable: true, checkFalsy: true}).isIn(['asc', 'desc']),
32
- query('search').trim().optional({nullable: true, checkFalsy: true}).trim()
31
+ query('search').trim().optional({nullable: true, checkFalsy: true}).trim(),
32
+ checkValidationResult,
33
33
  ], async (req, res) => {
34
- const result = validationResult(req);
35
- if (!result.isEmpty())
36
- return void res.status(400).json({errors: result.array()});
37
34
  const data = await UserModel.paginate(req.query);
38
35
  data.draw = req.query.draw;
39
36
  res.json(data);
@@ -41,11 +38,9 @@ router.get('/', [
41
38
 
42
39
  router.get('/email-exists', [
43
40
  query('user.email').trim().not().isEmpty(),
44
- query('excludeUserId').optional({nullable: true, checkFalsy: true}).isInt({min: 1})
41
+ query('excludeUserId').optional({nullable: true, checkFalsy: true}).isInt({min: 1}),
42
+ checkValidationResult,
45
43
  ], async (req, res) => {
46
- const result = validationResult(req);
47
- if (!result.isEmpty())
48
- return void res.status(400).json({errors: result.array()});
49
44
  const emailExists = await UserModel.emailExists(req.query.user.email, req.query.excludeUserId || null);
50
45
  res.json({valid: !emailExists});
51
46
  });
@@ -54,11 +49,9 @@ router.post('/', [
54
49
  body('user.email').trim().not().isEmpty().isEmail(),
55
50
  body('user.name').trim().not().isEmpty().isLength({max: 30}),
56
51
  body('user.password').trim().not().isEmpty().isLength({max: 128}),
57
- body('user.icon').not().isEmpty().custom(CustomValidation.isImageDataUrl)
52
+ body('user.icon').not().isEmpty().custom(isValidImageDataUrl),
53
+ checkValidationResult,
58
54
  ], async (req, res) => {
59
- const result = validationResult(req);
60
- if (!result.isEmpty())
61
- return void res.status(400).json({errors: result.array()});
62
55
  await UserModel.createUser(req.body.user);
63
56
  res.json(true);
64
57
  });
@@ -72,12 +65,10 @@ router.put('/:userId(\\d+)', [
72
65
  body('user.email').trim().not().isEmpty().isEmail(),
73
66
  body('user.name').trim().not().isEmpty().isLength({max: 30}),
74
67
  body('user.password').trim().optional({nullable: true, checkFalsy: true}).isLength({max: 128}),
75
- body('user.icon').not().isEmpty().custom(CustomValidation.isImageDataUrl)
68
+ body('user.icon').not().isEmpty().custom(isValidImageDataUrl),
69
+ checkValidationResult,
76
70
  ], async (req, res, next) => {
77
71
  try {
78
- const result = validationResult(req);
79
- if (!result.isEmpty())
80
- return void res.status(400).json({errors: result.array()});
81
72
  await UserModel.updateUser(req.params.userId, req.body.user);
82
73
  res.json(true);
83
74
  } catch (error) {
@@ -97,12 +88,10 @@ router.put('/profile', [
97
88
  body('user.email').trim().not().isEmpty().isEmail(),
98
89
  body('user.name').trim().not().isEmpty().isLength({max: 30}),
99
90
  body('user.password').trim().optional({nullable: true, checkFalsy: true}).isLength({max: 128}),
100
- body('user.icon').not().isEmpty().custom(CustomValidation.isImageDataUrl)
91
+ body('user.icon').not().isEmpty().custom(isValidImageDataUrl),
92
+ checkValidationResult,
101
93
  ], async (req, res, next) => {
102
94
  try {
103
- const result = validationResult(req);
104
- if (!result.isEmpty())
105
- return void res.status(400).json({errors: result.array()});
106
95
  await UserModel.updateUser(req.user.id, req.body.user);
107
96
  res.json(true);
108
97
  } catch (error) {
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Checks if a string is empty or contains only whitespace characters.
3
+ * @param {string|null|false} str The string to check.
4
+ * @return {boolean} True if the string is empty or contains only whitespace, false otherwise.
5
+ */
6
+ export default str => {
7
+ if (str == null || str === false)
8
+ return true;
9
+ return str.toString().trim() === '';
10
+ }
@@ -0,0 +1,16 @@
1
+ import isEmpty from '../shared/isEmpty.js';
2
+
3
+ /**
4
+ * Validates if a value is a valid image Data URL.
5
+ * @param {string} value The value to validate.
6
+ * @return {boolean} True if the value is a valid image Data URL or empty, otherwise throws an error.
7
+ * @throws {Error} If the value is not a valid image Data URL format.
8
+ */
9
+ export default value => {
10
+ if (isEmpty(value))
11
+ return true; // Empty values are considered valid
12
+ const dataUrlRegex = /^data:image\/[\w-+\d.]+;\w+,/;
13
+ if (!dataUrlRegex.test(value))
14
+ throw new Error('Invalid image Data URL format.');
15
+ return true;
16
+ }
@@ -1,12 +0,0 @@
1
- const empty = require('./empty');
2
-
3
- /**
4
- * Image Data URL validation.
5
- */
6
- exports.isImageDataUrl = function(value) {
7
- if (empty(value))
8
- return true;
9
- if (!value.match(/^data:image\/[\w-+\d.]+;\w+,/))
10
- throw new Error('Invalid as image Data URL');
11
- return true;
12
- }
@@ -1,8 +0,0 @@
1
- /**
2
- * Returns true if the string is empty, false otherwise.
3
- */
4
- module.exports = str => {
5
- if (str == null || str === false)
6
- return true;
7
- return str.toString().replace(/^[\s ]+|[\s ]+$/g, '') === '';
8
- }
@@ -1,12 +0,0 @@
1
- import empty from './empty.js';
2
-
3
- /**
4
- * Image Data URL validation.
5
- */
6
- export function isImageDataUrl(value) {
7
- if (empty(value))
8
- return true;
9
- if (!value.match(/^data:image\/[\w-+\d.]+;\w+,/))
10
- throw new Error('Invalid as image Data URL');
11
- return true;
12
- }
@@ -1,8 +0,0 @@
1
- /**
2
- * Returns true if the string is empty, false otherwise.
3
- */
4
- export default str => {
5
- if (str == null || str === false)
6
- return true;
7
- return str.toString().replace(/^[\s ]+|[\s ]+$/g, '') === '';
8
- }