create-charcole 2.2.0 → 2.2.2
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/.github/workflows/release.yml +26 -26
- package/CHANGELOG.md +301 -301
- package/LICENSE +21 -21
- package/README.md +357 -354
- package/bin/index.js +494 -444
- package/bin/lib/pkgManager.js +49 -49
- package/bin/lib/templateHandler.js +33 -33
- package/package.json +42 -27
- package/packages/swagger/BACKWARD_COMPATIBILITY.md +1 -1
- package/packages/swagger/CHANGELOG.md +1 -1
- package/packages/swagger/README.md +3 -3
- package/packages/swagger/package.json +57 -44
- package/packages/swagger/src/index.d.ts +126 -126
- package/packages/swagger/src/index.js +12 -12
- package/packages/swagger/src/setup.js +100 -100
- package/template/js/.env.example +16 -15
- package/template/js/README.md +982 -978
- package/template/js/basePackage.json +26 -26
- package/template/js/src/app.js +81 -81
- package/template/js/src/config/constants.js +20 -20
- package/template/js/src/config/env.js +26 -26
- package/template/js/src/config/swagger.config.js +15 -15
- package/template/js/src/lib/swagger/SWAGGER_GUIDE.md +3 -3
- package/template/js/src/middlewares/errorHandler.js +180 -180
- package/template/js/src/middlewares/requestLogger.js +33 -33
- package/template/js/src/middlewares/validateRequest.js +42 -42
- package/template/js/src/modules/auth/auth.constants.js +3 -3
- package/template/js/src/modules/auth/auth.controller.js +29 -29
- package/template/js/src/modules/auth/auth.middlewares.js +19 -19
- package/template/js/src/modules/auth/auth.routes.js +131 -131
- package/template/js/src/modules/auth/auth.schemas.js +60 -60
- package/template/js/src/modules/auth/auth.service.js +67 -67
- package/template/js/src/modules/auth/package.json +6 -6
- package/template/js/src/modules/health/controller.js +151 -151
- package/template/js/src/modules/swagger/package.json +5 -5
- package/template/js/src/repositories/user.repo.js +19 -19
- package/template/js/src/routes/index.js +25 -25
- package/template/js/src/routes/protected.js +57 -57
- package/template/js/src/server.js +38 -38
- package/template/js/src/utils/AppError.js +182 -182
- package/template/js/src/utils/logger.js +73 -73
- package/template/js/src/utils/response.js +51 -51
- package/template/ts/.env.example +16 -15
- package/template/ts/README.md +982 -978
- package/template/ts/basePackage.json +36 -36
- package/template/ts/build.js +46 -46
- package/template/ts/src/app.ts +71 -71
- package/template/ts/src/config/constants.ts +27 -27
- package/template/ts/src/config/env.ts +40 -40
- package/template/ts/src/config/swagger.config.ts +30 -30
- package/template/ts/src/lib/swagger/SWAGGER_GUIDE.md +2 -2
- package/template/ts/src/middlewares/errorHandler.ts +201 -201
- package/template/ts/src/middlewares/requestLogger.ts +38 -38
- package/template/ts/src/middlewares/validateRequest.ts +46 -46
- package/template/ts/src/modules/auth/auth.constants.ts +6 -6
- package/template/ts/src/modules/auth/auth.controller.ts +32 -32
- package/template/ts/src/modules/auth/auth.middlewares.ts +46 -46
- package/template/ts/src/modules/auth/auth.routes.ts +52 -52
- package/template/ts/src/modules/auth/auth.schemas.ts +73 -73
- package/template/ts/src/modules/auth/auth.service.ts +106 -106
- package/template/ts/src/modules/auth/package.json +10 -10
- package/template/ts/src/modules/health/controller.ts +80 -80
- package/template/ts/src/modules/swagger/package.json +5 -5
- package/template/ts/src/repositories/user.repo.ts +33 -33
- package/template/ts/src/routes/index.ts +24 -24
- package/template/ts/src/routes/protected.ts +46 -46
- package/template/ts/src/server.ts +41 -41
- package/template/ts/src/types/express.d.ts +9 -9
- package/template/ts/src/utils/AppError.ts +220 -220
- package/template/ts/src/utils/logger.ts +55 -55
- package/template/ts/src/utils/response.ts +100 -100
- package/template/ts/tsconfig.json +26 -26
- package/packages/swagger/package-lock.json +0 -1715
- package/tmpclaude-1049-cwd +0 -1
- package/tmpclaude-3e37-cwd +0 -1
- package/tmpclaude-4d73-cwd +0 -1
- package/tmpclaude-8a8e-cwd +0 -1
|
@@ -1,180 +1,180 @@
|
|
|
1
|
-
import { ZodError } from "zod";
|
|
2
|
-
import { HTTP_STATUS, ERROR_MESSAGES } from "../config/constants.js";
|
|
3
|
-
import { logger } from "../utils/logger.js";
|
|
4
|
-
import {
|
|
5
|
-
AppError,
|
|
6
|
-
ValidationError,
|
|
7
|
-
InternalServerError,
|
|
8
|
-
} from "../utils/AppError.js";
|
|
9
|
-
import { env } from "../config/env.js";
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Normalize different error types to AppError
|
|
13
|
-
*/
|
|
14
|
-
const normalizeError = (err) => {
|
|
15
|
-
// Already an AppError
|
|
16
|
-
if (err instanceof AppError) {
|
|
17
|
-
return err;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
// Zod validation error
|
|
21
|
-
if (err instanceof ZodError) {
|
|
22
|
-
const errors = err.errors.map((e) => ({
|
|
23
|
-
field: e.path.join("."),
|
|
24
|
-
message: e.message,
|
|
25
|
-
code: e.code,
|
|
26
|
-
}));
|
|
27
|
-
return new ValidationError(ERROR_MESSAGES.VALIDATION_ERROR, errors);
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
// Syntax errors (programmer error)
|
|
31
|
-
if (err instanceof SyntaxError) {
|
|
32
|
-
return new InternalServerError("Syntax error in application code", err, {
|
|
33
|
-
type: "SyntaxError",
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
// Type errors (programmer error)
|
|
38
|
-
if (err instanceof TypeError) {
|
|
39
|
-
return new InternalServerError("Type error in application", err, {
|
|
40
|
-
type: "TypeError",
|
|
41
|
-
});
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// Reference errors (programmer error)
|
|
45
|
-
if (err instanceof ReferenceError) {
|
|
46
|
-
return new InternalServerError("Reference error in application", err, {
|
|
47
|
-
type: "ReferenceError",
|
|
48
|
-
});
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// Range errors
|
|
52
|
-
if (err instanceof RangeError) {
|
|
53
|
-
return new InternalServerError("Range error in application", err, {
|
|
54
|
-
type: "RangeError",
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// Generic error (unknown)
|
|
59
|
-
return new InternalServerError(
|
|
60
|
-
err.message || ERROR_MESSAGES.SERVER_ERROR,
|
|
61
|
-
err,
|
|
62
|
-
{ type: "UnknownError" },
|
|
63
|
-
);
|
|
64
|
-
};
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* Log error based on type (operational vs programmer)
|
|
68
|
-
*/
|
|
69
|
-
const logError = (appError, req) => {
|
|
70
|
-
const errorDetails = {
|
|
71
|
-
type: appError.isOperational ? "OPERATIONAL" : "PROGRAMMER",
|
|
72
|
-
code: appError.code,
|
|
73
|
-
message: appError.message,
|
|
74
|
-
statusCode: appError.statusCode,
|
|
75
|
-
method: req.method,
|
|
76
|
-
path: req.path,
|
|
77
|
-
query: req.query,
|
|
78
|
-
ip: req.ip,
|
|
79
|
-
userAgent: req.get("user-agent"),
|
|
80
|
-
};
|
|
81
|
-
|
|
82
|
-
// Operational errors: normal logging
|
|
83
|
-
if (appError.isOperational) {
|
|
84
|
-
logger.warn(`Operational Error: ${appError.code}`, errorDetails);
|
|
85
|
-
} else {
|
|
86
|
-
// Programmer errors: detailed logging with stack
|
|
87
|
-
logger.error(
|
|
88
|
-
`Programmer Error: ${appError.code}`,
|
|
89
|
-
errorDetails,
|
|
90
|
-
appError.stack,
|
|
91
|
-
);
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
// Log validation errors separately
|
|
95
|
-
if (appError instanceof ValidationError && appError.errors) {
|
|
96
|
-
logger.debug("Validation errors", { errors: appError.errors });
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
// Log cause if present
|
|
100
|
-
if (appError.cause) {
|
|
101
|
-
logger.debug("Error cause", { cause: appError.cause.message });
|
|
102
|
-
}
|
|
103
|
-
};
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* Send error response
|
|
107
|
-
*/
|
|
108
|
-
const sendErrorResponse = (res, appError) => {
|
|
109
|
-
const statusCode = appError.statusCode || HTTP_STATUS.INTERNAL_SERVER_ERROR;
|
|
110
|
-
|
|
111
|
-
// In production, hide internal details for programmer errors
|
|
112
|
-
if (!appError.isOperational && env.isProduction) {
|
|
113
|
-
return res.status(statusCode).json({
|
|
114
|
-
success: false,
|
|
115
|
-
message: ERROR_MESSAGES.SERVER_ERROR,
|
|
116
|
-
code: "INTERNAL_SERVER_ERROR",
|
|
117
|
-
timestamp: new Date().toISOString(),
|
|
118
|
-
});
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// Return detailed error in development
|
|
122
|
-
const response = appError.toJSON
|
|
123
|
-
? appError.toJSON()
|
|
124
|
-
: {
|
|
125
|
-
success: false,
|
|
126
|
-
message: appError.message,
|
|
127
|
-
code: appError.code,
|
|
128
|
-
statusCode,
|
|
129
|
-
timestamp: new Date().toISOString(),
|
|
130
|
-
};
|
|
131
|
-
|
|
132
|
-
return res.status(statusCode).json(response);
|
|
133
|
-
};
|
|
134
|
-
|
|
135
|
-
/**
|
|
136
|
-
* Global Error Handler Middleware
|
|
137
|
-
*
|
|
138
|
-
* This middleware catches all errors and provides a unified way to handle them.
|
|
139
|
-
* MUST be the last middleware in the app.
|
|
140
|
-
*
|
|
141
|
-
* Features:
|
|
142
|
-
* - Distinguishes between operational and programmer errors
|
|
143
|
-
* - Logs errors with full context
|
|
144
|
-
* - Hides sensitive info in production
|
|
145
|
-
* - Formats JSON responses consistently
|
|
146
|
-
*/
|
|
147
|
-
export const errorHandler = (err, req, res, next) => {
|
|
148
|
-
// Normalize the error
|
|
149
|
-
const appError = normalizeError(err);
|
|
150
|
-
|
|
151
|
-
// Log the error
|
|
152
|
-
logError(appError, req);
|
|
153
|
-
|
|
154
|
-
// Send response
|
|
155
|
-
sendErrorResponse(res, appError);
|
|
156
|
-
};
|
|
157
|
-
|
|
158
|
-
/**
|
|
159
|
-
* Async error wrapper
|
|
160
|
-
* Wrap async route handlers to catch errors and pass to middleware
|
|
161
|
-
*
|
|
162
|
-
* Example:
|
|
163
|
-
* router.get('/users/:id', asyncHandler(getUserHandler))
|
|
164
|
-
*/
|
|
165
|
-
export const asyncHandler = (fn) => {
|
|
166
|
-
return (req, res, next) => {
|
|
167
|
-
return Promise.resolve(fn(req, res, next)).catch(next);
|
|
168
|
-
};
|
|
169
|
-
};
|
|
170
|
-
|
|
171
|
-
export {
|
|
172
|
-
AppError,
|
|
173
|
-
ValidationError,
|
|
174
|
-
InternalServerError,
|
|
175
|
-
AuthenticationError,
|
|
176
|
-
AuthorizationError,
|
|
177
|
-
NotFoundError,
|
|
178
|
-
ConflictError,
|
|
179
|
-
BadRequestError,
|
|
180
|
-
} from "../utils/AppError.js";
|
|
1
|
+
import { ZodError } from "zod";
|
|
2
|
+
import { HTTP_STATUS, ERROR_MESSAGES } from "../config/constants.js";
|
|
3
|
+
import { logger } from "../utils/logger.js";
|
|
4
|
+
import {
|
|
5
|
+
AppError,
|
|
6
|
+
ValidationError,
|
|
7
|
+
InternalServerError,
|
|
8
|
+
} from "../utils/AppError.js";
|
|
9
|
+
import { env } from "../config/env.js";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Normalize different error types to AppError
|
|
13
|
+
*/
|
|
14
|
+
const normalizeError = (err) => {
|
|
15
|
+
// Already an AppError
|
|
16
|
+
if (err instanceof AppError) {
|
|
17
|
+
return err;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Zod validation error
|
|
21
|
+
if (err instanceof ZodError) {
|
|
22
|
+
const errors = err.errors.map((e) => ({
|
|
23
|
+
field: e.path.join("."),
|
|
24
|
+
message: e.message,
|
|
25
|
+
code: e.code,
|
|
26
|
+
}));
|
|
27
|
+
return new ValidationError(ERROR_MESSAGES.VALIDATION_ERROR, errors);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Syntax errors (programmer error)
|
|
31
|
+
if (err instanceof SyntaxError) {
|
|
32
|
+
return new InternalServerError("Syntax error in application code", err, {
|
|
33
|
+
type: "SyntaxError",
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Type errors (programmer error)
|
|
38
|
+
if (err instanceof TypeError) {
|
|
39
|
+
return new InternalServerError("Type error in application", err, {
|
|
40
|
+
type: "TypeError",
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Reference errors (programmer error)
|
|
45
|
+
if (err instanceof ReferenceError) {
|
|
46
|
+
return new InternalServerError("Reference error in application", err, {
|
|
47
|
+
type: "ReferenceError",
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Range errors
|
|
52
|
+
if (err instanceof RangeError) {
|
|
53
|
+
return new InternalServerError("Range error in application", err, {
|
|
54
|
+
type: "RangeError",
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Generic error (unknown)
|
|
59
|
+
return new InternalServerError(
|
|
60
|
+
err.message || ERROR_MESSAGES.SERVER_ERROR,
|
|
61
|
+
err,
|
|
62
|
+
{ type: "UnknownError" },
|
|
63
|
+
);
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Log error based on type (operational vs programmer)
|
|
68
|
+
*/
|
|
69
|
+
const logError = (appError, req) => {
|
|
70
|
+
const errorDetails = {
|
|
71
|
+
type: appError.isOperational ? "OPERATIONAL" : "PROGRAMMER",
|
|
72
|
+
code: appError.code,
|
|
73
|
+
message: appError.message,
|
|
74
|
+
statusCode: appError.statusCode,
|
|
75
|
+
method: req.method,
|
|
76
|
+
path: req.path,
|
|
77
|
+
query: req.query,
|
|
78
|
+
ip: req.ip,
|
|
79
|
+
userAgent: req.get("user-agent"),
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// Operational errors: normal logging
|
|
83
|
+
if (appError.isOperational) {
|
|
84
|
+
logger.warn(`Operational Error: ${appError.code}`, errorDetails);
|
|
85
|
+
} else {
|
|
86
|
+
// Programmer errors: detailed logging with stack
|
|
87
|
+
logger.error(
|
|
88
|
+
`Programmer Error: ${appError.code}`,
|
|
89
|
+
errorDetails,
|
|
90
|
+
appError.stack,
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Log validation errors separately
|
|
95
|
+
if (appError instanceof ValidationError && appError.errors) {
|
|
96
|
+
logger.debug("Validation errors", { errors: appError.errors });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Log cause if present
|
|
100
|
+
if (appError.cause) {
|
|
101
|
+
logger.debug("Error cause", { cause: appError.cause.message });
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Send error response
|
|
107
|
+
*/
|
|
108
|
+
const sendErrorResponse = (res, appError) => {
|
|
109
|
+
const statusCode = appError.statusCode || HTTP_STATUS.INTERNAL_SERVER_ERROR;
|
|
110
|
+
|
|
111
|
+
// In production, hide internal details for programmer errors
|
|
112
|
+
if (!appError.isOperational && env.isProduction) {
|
|
113
|
+
return res.status(statusCode).json({
|
|
114
|
+
success: false,
|
|
115
|
+
message: ERROR_MESSAGES.SERVER_ERROR,
|
|
116
|
+
code: "INTERNAL_SERVER_ERROR",
|
|
117
|
+
timestamp: new Date().toISOString(),
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Return detailed error in development
|
|
122
|
+
const response = appError.toJSON
|
|
123
|
+
? appError.toJSON()
|
|
124
|
+
: {
|
|
125
|
+
success: false,
|
|
126
|
+
message: appError.message,
|
|
127
|
+
code: appError.code,
|
|
128
|
+
statusCode,
|
|
129
|
+
timestamp: new Date().toISOString(),
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
return res.status(statusCode).json(response);
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Global Error Handler Middleware
|
|
137
|
+
*
|
|
138
|
+
* This middleware catches all errors and provides a unified way to handle them.
|
|
139
|
+
* MUST be the last middleware in the app.
|
|
140
|
+
*
|
|
141
|
+
* Features:
|
|
142
|
+
* - Distinguishes between operational and programmer errors
|
|
143
|
+
* - Logs errors with full context
|
|
144
|
+
* - Hides sensitive info in production
|
|
145
|
+
* - Formats JSON responses consistently
|
|
146
|
+
*/
|
|
147
|
+
export const errorHandler = (err, req, res, next) => {
|
|
148
|
+
// Normalize the error
|
|
149
|
+
const appError = normalizeError(err);
|
|
150
|
+
|
|
151
|
+
// Log the error
|
|
152
|
+
logError(appError, req);
|
|
153
|
+
|
|
154
|
+
// Send response
|
|
155
|
+
sendErrorResponse(res, appError);
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Async error wrapper
|
|
160
|
+
* Wrap async route handlers to catch errors and pass to middleware
|
|
161
|
+
*
|
|
162
|
+
* Example:
|
|
163
|
+
* router.get('/users/:id', asyncHandler(getUserHandler))
|
|
164
|
+
*/
|
|
165
|
+
export const asyncHandler = (fn) => {
|
|
166
|
+
return (req, res, next) => {
|
|
167
|
+
return Promise.resolve(fn(req, res, next)).catch(next);
|
|
168
|
+
};
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
export {
|
|
172
|
+
AppError,
|
|
173
|
+
ValidationError,
|
|
174
|
+
InternalServerError,
|
|
175
|
+
AuthenticationError,
|
|
176
|
+
AuthorizationError,
|
|
177
|
+
NotFoundError,
|
|
178
|
+
ConflictError,
|
|
179
|
+
BadRequestError,
|
|
180
|
+
} from "../utils/AppError.js";
|
|
@@ -1,33 +1,33 @@
|
|
|
1
|
-
import { logger } from "../utils/logger.js";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Request logging middleware
|
|
5
|
-
* Logs all HTTP requests with method, path, status, duration, and IP
|
|
6
|
-
*/
|
|
7
|
-
export const requestLogger = (req, res, next) => {
|
|
8
|
-
const start = Date.now();
|
|
9
|
-
|
|
10
|
-
res.on("finish", () => {
|
|
11
|
-
const duration = Date.now() - start;
|
|
12
|
-
const statusCode = res.statusCode;
|
|
13
|
-
const isError = statusCode >= 400;
|
|
14
|
-
|
|
15
|
-
const logData = {
|
|
16
|
-
method: req.method,
|
|
17
|
-
path: req.path,
|
|
18
|
-
statusCode,
|
|
19
|
-
durationMs: duration,
|
|
20
|
-
ip: req.ip,
|
|
21
|
-
userAgent: req.get("user-agent"),
|
|
22
|
-
...(isError && { error: true }),
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
if (isError) {
|
|
26
|
-
logger.warn(`${req.method} ${req.path}`, logData);
|
|
27
|
-
} else {
|
|
28
|
-
logger.debug(`${req.method} ${req.path}`, logData);
|
|
29
|
-
}
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
next();
|
|
33
|
-
};
|
|
1
|
+
import { logger } from "../utils/logger.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Request logging middleware
|
|
5
|
+
* Logs all HTTP requests with method, path, status, duration, and IP
|
|
6
|
+
*/
|
|
7
|
+
export const requestLogger = (req, res, next) => {
|
|
8
|
+
const start = Date.now();
|
|
9
|
+
|
|
10
|
+
res.on("finish", () => {
|
|
11
|
+
const duration = Date.now() - start;
|
|
12
|
+
const statusCode = res.statusCode;
|
|
13
|
+
const isError = statusCode >= 400;
|
|
14
|
+
|
|
15
|
+
const logData = {
|
|
16
|
+
method: req.method,
|
|
17
|
+
path: req.path,
|
|
18
|
+
statusCode,
|
|
19
|
+
durationMs: duration,
|
|
20
|
+
ip: req.ip,
|
|
21
|
+
userAgent: req.get("user-agent"),
|
|
22
|
+
...(isError && { error: true }),
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
if (isError) {
|
|
26
|
+
logger.warn(`${req.method} ${req.path}`, logData);
|
|
27
|
+
} else {
|
|
28
|
+
logger.debug(`${req.method} ${req.path}`, logData);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
next();
|
|
33
|
+
};
|
|
@@ -1,42 +1,42 @@
|
|
|
1
|
-
import { ValidationError } from "../utils/AppError.js";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Request validation middleware
|
|
5
|
-
*
|
|
6
|
-
* Validates request body, query, and params against a Zod schema
|
|
7
|
-
* Throws ValidationError if validation fails
|
|
8
|
-
*
|
|
9
|
-
* Example:
|
|
10
|
-
* const schema = z.object({
|
|
11
|
-
* body: z.object({ name: z.string() }),
|
|
12
|
-
* query: z.object({ page: z.coerce.number().optional() }),
|
|
13
|
-
* });
|
|
14
|
-
*
|
|
15
|
-
* router.post('/items', validateRequest(schema), handler)
|
|
16
|
-
*/
|
|
17
|
-
export const validateRequest = (schema) => {
|
|
18
|
-
return async (req, res, next) => {
|
|
19
|
-
try {
|
|
20
|
-
// Validate request
|
|
21
|
-
const validated = await schema.parseAsync({
|
|
22
|
-
body: req.body,
|
|
23
|
-
query: req.query,
|
|
24
|
-
params: req.params,
|
|
25
|
-
});
|
|
26
|
-
|
|
27
|
-
// Attach validated data
|
|
28
|
-
req.validatedData = validated;
|
|
29
|
-
next();
|
|
30
|
-
} catch (error) {
|
|
31
|
-
if (error.name === "ZodError") {
|
|
32
|
-
const errors = error.errors.map((e) => ({
|
|
33
|
-
field: e.path.join("."),
|
|
34
|
-
message: e.message,
|
|
35
|
-
code: e.code,
|
|
36
|
-
}));
|
|
37
|
-
throw new ValidationError("Request validation failed", errors);
|
|
38
|
-
}
|
|
39
|
-
next(error);
|
|
40
|
-
}
|
|
41
|
-
};
|
|
42
|
-
};
|
|
1
|
+
import { ValidationError } from "../utils/AppError.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Request validation middleware
|
|
5
|
+
*
|
|
6
|
+
* Validates request body, query, and params against a Zod schema
|
|
7
|
+
* Throws ValidationError if validation fails
|
|
8
|
+
*
|
|
9
|
+
* Example:
|
|
10
|
+
* const schema = z.object({
|
|
11
|
+
* body: z.object({ name: z.string() }),
|
|
12
|
+
* query: z.object({ page: z.coerce.number().optional() }),
|
|
13
|
+
* });
|
|
14
|
+
*
|
|
15
|
+
* router.post('/items', validateRequest(schema), handler)
|
|
16
|
+
*/
|
|
17
|
+
export const validateRequest = (schema) => {
|
|
18
|
+
return async (req, res, next) => {
|
|
19
|
+
try {
|
|
20
|
+
// Validate request
|
|
21
|
+
const validated = await schema.parseAsync({
|
|
22
|
+
body: req.body,
|
|
23
|
+
query: req.query,
|
|
24
|
+
params: req.params,
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
// Attach validated data
|
|
28
|
+
req.validatedData = validated;
|
|
29
|
+
next();
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (error.name === "ZodError") {
|
|
32
|
+
const errors = error.errors.map((e) => ({
|
|
33
|
+
field: e.path.join("."),
|
|
34
|
+
message: e.message,
|
|
35
|
+
code: e.code,
|
|
36
|
+
}));
|
|
37
|
+
throw new ValidationError("Request validation failed", errors);
|
|
38
|
+
}
|
|
39
|
+
next(error);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export const USER_ROLES = ["user", "admin"];
|
|
2
|
-
|
|
3
|
-
export const AUTH_PROVIDERS = ["credentials"];
|
|
1
|
+
export const USER_ROLES = ["user", "admin"];
|
|
2
|
+
|
|
3
|
+
export const AUTH_PROVIDERS = ["credentials"];
|
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
import { AuthService } from "./auth.service.js";
|
|
2
|
-
|
|
3
|
-
export const AuthController = {
|
|
4
|
-
async register(req, res) {
|
|
5
|
-
try {
|
|
6
|
-
const user = await AuthService.register(
|
|
7
|
-
req.body,
|
|
8
|
-
req.app.locals.userRepo,
|
|
9
|
-
);
|
|
10
|
-
|
|
11
|
-
res.status(201).json({
|
|
12
|
-
message: "User registered successfully",
|
|
13
|
-
user,
|
|
14
|
-
});
|
|
15
|
-
} catch (err) {
|
|
16
|
-
res.status(400).json({ message: err.message });
|
|
17
|
-
}
|
|
18
|
-
},
|
|
19
|
-
|
|
20
|
-
async login(req, res) {
|
|
21
|
-
try {
|
|
22
|
-
const result = await AuthService.login(req.body, req.app.locals.userRepo);
|
|
23
|
-
|
|
24
|
-
res.json(result);
|
|
25
|
-
} catch (err) {
|
|
26
|
-
res.status(401).json({ message: err.message });
|
|
27
|
-
}
|
|
28
|
-
},
|
|
29
|
-
};
|
|
1
|
+
import { AuthService } from "./auth.service.js";
|
|
2
|
+
|
|
3
|
+
export const AuthController = {
|
|
4
|
+
async register(req, res) {
|
|
5
|
+
try {
|
|
6
|
+
const user = await AuthService.register(
|
|
7
|
+
req.body,
|
|
8
|
+
req.app.locals.userRepo,
|
|
9
|
+
);
|
|
10
|
+
|
|
11
|
+
res.status(201).json({
|
|
12
|
+
message: "User registered successfully",
|
|
13
|
+
user,
|
|
14
|
+
});
|
|
15
|
+
} catch (err) {
|
|
16
|
+
res.status(400).json({ message: err.message });
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
|
|
20
|
+
async login(req, res) {
|
|
21
|
+
try {
|
|
22
|
+
const result = await AuthService.login(req.body, req.app.locals.userRepo);
|
|
23
|
+
|
|
24
|
+
res.json(result);
|
|
25
|
+
} catch (err) {
|
|
26
|
+
res.status(401).json({ message: err.message });
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
};
|
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import jwt from "jsonwebtoken";
|
|
2
|
-
|
|
3
|
-
export const requireAuth = (req, res, next) => {
|
|
4
|
-
const authHeader = req.headers.authorization;
|
|
5
|
-
|
|
6
|
-
if (!authHeader?.startsWith("Bearer ")) {
|
|
7
|
-
return res.status(401).json({ message: "Unauthorized" });
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
const token = authHeader.split(" ")[1];
|
|
11
|
-
|
|
12
|
-
try {
|
|
13
|
-
const payload = jwt.verify(token, process.env.JWT_SECRET);
|
|
14
|
-
req.user = payload;
|
|
15
|
-
next();
|
|
16
|
-
} catch {
|
|
17
|
-
res.status(401).json({ message: "Invalid token" });
|
|
18
|
-
}
|
|
19
|
-
};
|
|
1
|
+
import jwt from "jsonwebtoken";
|
|
2
|
+
|
|
3
|
+
export const requireAuth = (req, res, next) => {
|
|
4
|
+
const authHeader = req.headers.authorization;
|
|
5
|
+
|
|
6
|
+
if (!authHeader?.startsWith("Bearer ")) {
|
|
7
|
+
return res.status(401).json({ message: "Unauthorized" });
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const token = authHeader.split(" ")[1];
|
|
11
|
+
|
|
12
|
+
try {
|
|
13
|
+
const payload = jwt.verify(token, process.env.JWT_SECRET);
|
|
14
|
+
req.user = payload;
|
|
15
|
+
next();
|
|
16
|
+
} catch {
|
|
17
|
+
res.status(401).json({ message: "Invalid token" });
|
|
18
|
+
}
|
|
19
|
+
};
|