moahmedwafy commited on
Commit
9702c40
·
unverified ·
2 Parent(s): b798149 67bacb2

Merge pull request #41 from Modarb-Ai-Trainer:MoWafy001/issue35

Browse files
src/lib/services/crud.service.ts CHANGED
@@ -11,14 +11,26 @@ export const CrudService = <ModelDoc extends Document>(
11
  return this.model.create(data);
12
  }
13
 
14
- async update(
15
  filter: FilterQuery<ModelDoc>,
16
  data: AnyKeys<ModelDoc>
17
  ): Promise<ModelDoc> {
18
- return this.model.findOneAndUpdate(filter, data, { new: true });
 
 
19
  }
20
 
21
- async delete(filter: FilterQuery<ModelDoc>): Promise<ModelDoc> {
 
 
 
 
 
 
 
 
 
 
22
  return this.model.findOneAndDelete(filter);
23
  }
24
 
@@ -59,10 +71,16 @@ export const CrudService = <ModelDoc extends Document>(
59
  }
60
 
61
  async findOneOrFail(filter: FilterQuery<ModelDoc>): Promise<ModelDoc> {
 
62
  const document = await this.findOne(filter);
63
- if (!document) throw new HttpError(404, "No Matching Result Found.");
64
 
65
  return document;
66
  }
 
 
 
 
 
 
67
  };
68
  };
 
11
  return this.model.create(data);
12
  }
13
 
14
+ async updateOne(
15
  filter: FilterQuery<ModelDoc>,
16
  data: AnyKeys<ModelDoc>
17
  ): Promise<ModelDoc> {
18
+ await this.existsOrThrow(filter);
19
+ await this.model.updateOne(filter, data);
20
+ return this.findOneOrFail(filter);
21
  }
22
 
23
+ async updateMany(
24
+ filter: FilterQuery<ModelDoc>,
25
+ data: AnyKeys<ModelDoc>
26
+ ): Promise<ModelDoc[]> {
27
+ await this.existsOrThrow(filter);
28
+ await this.model.updateMany(filter, data);
29
+ return this.model.find(filter);
30
+ }
31
+
32
+ async deleteOne(filter: FilterQuery<ModelDoc>): Promise<ModelDoc> {
33
+ await this.existsOrThrow(filter);
34
  return this.model.findOneAndDelete(filter);
35
  }
36
 
 
71
  }
72
 
73
  async findOneOrFail(filter: FilterQuery<ModelDoc>): Promise<ModelDoc> {
74
+ await this.existsOrThrow(filter);
75
  const document = await this.findOne(filter);
 
76
 
77
  return document;
78
  }
79
+
80
+ private async existsOrThrow(filter: FilterQuery<ModelDoc>) {
81
+ if (!(await this.model.exists(filter))) {
82
+ throw new HttpError(404, "No Matching Result Found.");
83
+ }
84
+ }
85
  };
86
  };
src/middlewares/error-handler.middleware.ts ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { JsonResponse } from "@lib/responses/json-response";
2
+ import { NextFunction, Request, Response } from "express";
3
+ import { Error as MongooseError } from "mongoose";
4
+
5
+ export const errorHandlerMiddleware = (
6
+ err: MongooseError | any,
7
+ req: Request,
8
+ res: Response,
9
+ next: NextFunction
10
+ ) => {
11
+ let errorMessage = err.message;
12
+ let status = err.status || 500;
13
+ console.log("errorHandlerMiddleware -> err", err);
14
+
15
+ if (err.code === 11000) {
16
+ // Handle validation errors
17
+ const errors = [];
18
+ try {
19
+ const errorInKeys = Object.keys(err.keyValue);
20
+ errorInKeys.forEach((key) => {
21
+ errors.push(`${key} already exists`);
22
+ });
23
+ } catch (error) {
24
+ errors.push("Duplicate key error");
25
+ }
26
+ return JsonResponse.validationError(
27
+ {
28
+ errors,
29
+ },
30
+ res
31
+ );
32
+ } else if (err.code === 66) {
33
+ // Handle cast errors
34
+ status = 400;
35
+ if (err.path) {
36
+ errorMessage = `Invalid ${err.path}`;
37
+ } else {
38
+ errorMessage = "Invalid data";
39
+ }
40
+ } else if (err.code === 2) {
41
+ // Handle other mongoose errors
42
+ status = 400;
43
+ if (err.message) {
44
+ errorMessage = err.message;
45
+ } else {
46
+ errorMessage = "Invalid data";
47
+ }
48
+ }
49
+
50
+ JsonResponse.error(
51
+ {
52
+ error: errorMessage,
53
+ status,
54
+ },
55
+ res
56
+ );
57
+
58
+ console.error(err.message, err.stack);
59
+ };
src/modules/console/modules/admins/controllers/admins.controller.ts CHANGED
@@ -81,7 +81,7 @@ export class AdminsController extends BaseController {
81
  };
82
 
83
  update = async (req: Request, res: Response): Promise<Response> => {
84
- const admin = await this.adminsService.update(
85
  {
86
  _id: req.params.id,
87
  },
@@ -97,7 +97,7 @@ export class AdminsController extends BaseController {
97
  };
98
 
99
  delete = async (req: Request, res: Response): Promise<Response> => {
100
- const admin = await this.adminsService.delete({
101
  _id: req.params.id,
102
  });
103
 
 
81
  };
82
 
83
  update = async (req: Request, res: Response): Promise<Response> => {
84
+ const admin = await this.adminsService.updateOne(
85
  {
86
  _id: req.params.id,
87
  },
 
97
  };
98
 
99
  delete = async (req: Request, res: Response): Promise<Response> => {
100
+ const admin = await this.adminsService.deleteOne({
101
  _id: req.params.id,
102
  });
103
 
src/modules/console/modules/workouts/controllers/workouts.controller.ts CHANGED
@@ -78,7 +78,7 @@ export class WorkoutController extends BaseController {
78
  };
79
 
80
  update = async (req: Request, res: Response) => {
81
- const data = await this.workoutsService.update(
82
  { _id: req.params.id },
83
  req.body
84
  );
@@ -91,7 +91,7 @@ export class WorkoutController extends BaseController {
91
  };
92
 
93
  delete = async (req: Request, res: Response) => {
94
- const data = await this.workoutsService.delete({ _id: req.params.id });
95
  return JsonResponse.success(
96
  {
97
  data: serialize(data.toJSON(), WorkoutSerialization),
 
78
  };
79
 
80
  update = async (req: Request, res: Response) => {
81
+ const data = await this.workoutsService.updateOne(
82
  { _id: req.params.id },
83
  req.body
84
  );
 
91
  };
92
 
93
  delete = async (req: Request, res: Response) => {
94
+ const data = await this.workoutsService.deleteOne({ _id: req.params.id });
95
  return JsonResponse.success(
96
  {
97
  data: serialize(data.toJSON(), WorkoutSerialization),
src/routes.ts CHANGED
@@ -5,6 +5,7 @@ import path from "path";
5
  import { BaseController } from "./lib/controllers/controller.base";
6
  import { validationErrorHandler } from "./helpers/validation.helper";
7
  import { JsonResponse } from "@lib/responses/json-response";
 
8
 
9
  /**
10
  * Sets the routes for the Express app.
@@ -54,21 +55,7 @@ const setCustomRoutes = (router: Router) => {
54
  });
55
 
56
  // Error handler
57
- router.use((err, req, res, next) => {
58
- try {
59
- err.message = JSON.parse(err.message);
60
- } catch (error) {}
61
-
62
- JsonResponse.error(
63
- {
64
- error: err.message || "Internal Server Error",
65
- status: err.status || 500,
66
- },
67
- res
68
- );
69
-
70
- console.error(err.message, err.stack);
71
- });
72
  };
73
 
74
  /* importing all controllers */
 
5
  import { BaseController } from "./lib/controllers/controller.base";
6
  import { validationErrorHandler } from "./helpers/validation.helper";
7
  import { JsonResponse } from "@lib/responses/json-response";
8
+ import { errorHandlerMiddleware } from "middlewares/error-handler.middleware";
9
 
10
  /**
11
  * Sets the routes for the Express app.
 
55
  });
56
 
57
  // Error handler
58
+ router.use(errorHandlerMiddleware);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  };
60
 
61
  /* importing all controllers */