express-sweet-generator 2.0.6 → 2.0.8

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.
@@ -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
- const UserNotFound = require('../../exceptions/UserNotFound');
6
- const CustomValidation = require('../../shared/CustomValidation');
5
+ const NotFoundError = require('../../errors/NotFoundError');
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,16 +65,14 @@ 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) {
84
- if (error instanceof UserNotFound)
75
+ if (error instanceof NotFoundError)
85
76
  res.json({error: error.name});
86
77
  else
87
78
  next(error);
@@ -97,16 +88,14 @@ 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) {
109
- if (error instanceof UserNotFound)
98
+ if (error instanceof NotFoundError)
110
99
  res.json({error: error.name});
111
100
  else
112
101
  next(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
+ }
@@ -50,7 +50,7 @@ function initForm() {
50
50
  const {data} = await userApi.updateProfile(new FormData(validation.form));
51
51
  validation.offIndicator();
52
52
  if (data.error)
53
- if (data.error === 'UserNotFound') {
53
+ if (data.error === 'NotFoundError') {
54
54
  await components.Dialog.warning('The account you are using has been deleted and you will be forcibly logged out.');
55
55
  return void userApi.logout();
56
56
  } else
@@ -269,7 +269,7 @@ export default class extends components.Modal {
269
269
  // User update request.
270
270
  const {data} = await this.#userApi.updateUser(this.#userId, new FormData(this.#validator.form));
271
271
  this.#validator.offIndicator();
272
- if (data?.error === 'UserNotFound') {
272
+ if (data?.error === 'NotFoundError') {
273
273
  await components.Dialog.warning('This user has been deleted.');
274
274
  return void super.hide(true);
275
275
  }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Custom error class for "Not Found" errors.
3
+ */
4
+ export default class extends Error {
5
+ /**
6
+ * Creates a new NotFoundError instance.
7
+ * @param {string} [message='The requested record could not be found.'] - The error message.
8
+ */
9
+ constructor(message = 'The requested record could not be found.') {
10
+ super(message);
11
+ this.name = 'NotFoundError';
12
+ this.statusCode = 404; // HTTP status code for "Not Found"
13
+ }
14
+ }
@@ -0,0 +1,13 @@
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
+ res.status(400).end();
12
+ // res.status(400).json({errors: result.array()});
13
+ }
@@ -1,6 +1,6 @@
1
1
  import * as expressExtension from 'express-sweet';
2
2
  import {Media} from 'nodejs-shared';
3
- import UserNotFound from '../exceptions/UserNotFound.js';
3
+ import NotFoundError from '../errors/NotFoundError.js';
4
4
  import ProfileModel from './ProfileModel.js';
5
5
  import CommentModel from './CommentModel.js';
6
6
  import BookModel from './BookModel.js';
@@ -123,7 +123,7 @@ export default class extends expressExtension.database.Model {
123
123
  }, set);
124
124
  const user = await this.getUser(userId);
125
125
  if (!user)
126
- throw new UserNotFound();
126
+ throw new NotFoundError();
127
127
  transaction = await super.begin();
128
128
  user.email = set.email;
129
129
  user.name = set.name;