create-charcole 1.0.0

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.
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "charcole",
3
+ "version": "1.0.0",
4
+ "description": "Production-grade Node.js Express API",
5
+ "main": "src/server.js",
6
+ "scripts": {
7
+ "start": "node src/server.js",
8
+ "dev": "nodemon src/server.js",
9
+ "lint": "echo 'Add linting here'",
10
+ "test": "echo 'Add tests here'"
11
+ },
12
+ "engines": {
13
+ "node": ">=18.0.0"
14
+ },
15
+ "keywords": [],
16
+ "author": "",
17
+ "license": "ISC",
18
+ "type": "module",
19
+ "dependencies": {
20
+ "cors": "^2.8.5",
21
+ "dotenv": "^16.3.1",
22
+ "express": "^4.18.2",
23
+ "zod": "^3.22.4"
24
+ },
25
+ "devDependencies": {
26
+ "nodemon": "^3.0.2"
27
+ }
28
+ }
@@ -0,0 +1,75 @@
1
+ import express from "express";
2
+ import cors from "cors";
3
+ import { env } from "./config/env.js";
4
+ import { HTTP_STATUS, ERROR_MESSAGES } from "./config/constants.js";
5
+ import { requestLogger } from "./middlewares/requestLogger.js";
6
+ import {
7
+ errorHandler,
8
+ asyncHandler,
9
+ NotFoundError,
10
+ } from "./middlewares/errorHandler.js";
11
+ import { sendSuccess } from "./utils/response.js";
12
+ import { logger } from "./utils/logger.js";
13
+ import routes from "./routes.js";
14
+
15
+ export const app = express();
16
+
17
+ // Trust proxy
18
+ app.set("trust proxy", 1);
19
+
20
+ // CORS Configuration
21
+ app.use(
22
+ cors({
23
+ origin: env.CORS_ORIGIN,
24
+ credentials: true,
25
+ methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
26
+ allowedHeaders: ["Content-Type", "Authorization"],
27
+ }),
28
+ );
29
+
30
+ // Body parsing middleware
31
+ app.use(express.json({ limit: "10mb" }));
32
+ app.use(express.urlencoded({ extended: true, limit: "10mb" }));
33
+
34
+ // Request timeout
35
+ app.use((req, res, next) => {
36
+ req.setTimeout(env.REQUEST_TIMEOUT);
37
+ res.setTimeout(env.REQUEST_TIMEOUT);
38
+ next();
39
+ });
40
+
41
+ // Request logging
42
+ app.use(requestLogger);
43
+
44
+ // API Routes
45
+ app.use("/api", routes);
46
+
47
+ // Root health endpoint
48
+ app.get(
49
+ "/",
50
+ asyncHandler(async (req, res) => {
51
+ sendSuccess(
52
+ res,
53
+ {
54
+ message: "Welcome to Charcole API",
55
+ version: "1.0.0",
56
+ environment: env.NODE_ENV,
57
+ },
58
+ 200,
59
+ "API is online",
60
+ );
61
+ }),
62
+ );
63
+
64
+ // 404 handler
65
+ app.use((req, res, next) => {
66
+ throw new NotFoundError(`${req.method} ${req.path}`, {
67
+ method: req.method,
68
+ path: req.path,
69
+ });
70
+ });
71
+
72
+ // Global error handler (MUST be last)
73
+ app.use(errorHandler);
74
+
75
+ logger.info("Express app configured successfully");
@@ -0,0 +1,20 @@
1
+ export const HTTP_STATUS = {
2
+ OK: 200,
3
+ CREATED: 201,
4
+ BAD_REQUEST: 400,
5
+ UNAUTHORIZED: 401,
6
+ FORBIDDEN: 403,
7
+ NOT_FOUND: 404,
8
+ CONFLICT: 409,
9
+ UNPROCESSABLE_ENTITY: 422,
10
+ INTERNAL_SERVER_ERROR: 500,
11
+ SERVICE_UNAVAILABLE: 503,
12
+ };
13
+
14
+ export const ERROR_MESSAGES = {
15
+ VALIDATION_ERROR: "Validation failed",
16
+ NOT_FOUND: "Resource not found",
17
+ UNAUTHORIZED: "Unauthorized",
18
+ SERVER_ERROR: "Internal server error",
19
+ BAD_REQUEST: "Bad request",
20
+ };
@@ -0,0 +1,26 @@
1
+ import { z } from "zod";
2
+
3
+ const envSchema = z.object({
4
+ NODE_ENV: z
5
+ .enum(["development", "production", "test"])
6
+ .default("development"),
7
+ PORT: z.coerce.number().default(3000),
8
+ LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"),
9
+ CORS_ORIGIN: z.string().default("*"),
10
+ REQUEST_TIMEOUT: z.coerce.number().default(30000),
11
+ });
12
+
13
+ const parseEnv = () => {
14
+ try {
15
+ return envSchema.parse(process.env);
16
+ } catch (error) {
17
+ console.error("❌ Invalid environment variables:", error.errors);
18
+ process.exit(1);
19
+ }
20
+ };
21
+
22
+ export const env = parseEnv();
23
+
24
+ export const isDevelopment = env.NODE_ENV === "development";
25
+ export const isProduction = env.NODE_ENV === "production";
26
+ export const isTest = env.NODE_ENV === "test";
@@ -0,0 +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";
@@ -0,0 +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
+ };
@@ -0,0 +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
+ };
@@ -0,0 +1,50 @@
1
+ import { z } from "zod";
2
+ import { sendSuccess } from "../../utils/response.js";
3
+ import { asyncHandler } from "../../middlewares/errorHandler.js";
4
+
5
+ /**
6
+ * Health check endpoint
7
+ * Always returns healthy status (ping endpoint)
8
+ */
9
+ export const getHealth = asyncHandler(async (req, res) => {
10
+ sendSuccess(
11
+ res,
12
+ {
13
+ status: "healthy",
14
+ uptime: process.uptime(),
15
+ timestamp: new Date().toISOString(),
16
+ },
17
+ 200,
18
+ "Service is healthy",
19
+ );
20
+ });
21
+
22
+ /**
23
+ * Example POST endpoint with validation
24
+ * Demonstrates proper error handling with Zod validation
25
+ */
26
+ export const createItemSchema = z.object({
27
+ body: z.object({
28
+ name: z.string().min(1, "Name is required").max(100),
29
+ description: z.string().optional(),
30
+ }),
31
+ });
32
+
33
+ export const createItem = asyncHandler(async (req, res) => {
34
+ const { name, description } = req.validatedData.body;
35
+
36
+ // Simulate some async work
37
+ await new Promise((resolve) => setTimeout(resolve, 10));
38
+
39
+ sendSuccess(
40
+ res,
41
+ {
42
+ id: Math.random().toString(36).substr(2, 9),
43
+ name,
44
+ description: description || null,
45
+ createdAt: new Date().toISOString(),
46
+ },
47
+ 201,
48
+ "Item created successfully",
49
+ );
50
+ });
@@ -0,0 +1,17 @@
1
+ import { Router } from "express";
2
+ import {
3
+ getHealth,
4
+ createItem,
5
+ createItemSchema,
6
+ } from "./modules/health/controller.js";
7
+ import { validateRequest } from "./middlewares/validateRequest.js";
8
+
9
+ const router = Router();
10
+
11
+ // Health check
12
+ router.get("/health", getHealth);
13
+
14
+ // Example: Create item with validation
15
+ router.post("/items", validateRequest(createItemSchema), createItem);
16
+
17
+ export default router;
@@ -0,0 +1,38 @@
1
+ import "dotenv/config";
2
+
3
+ import { app } from "./app.js";
4
+ import { env } from "./config/env.js";
5
+ import { logger } from "./utils/logger.js";
6
+
7
+ const PORT = env.PORT;
8
+
9
+ const server = app.listen(PORT, () => {
10
+ logger.info(`🔥 Server running in ${env.NODE_ENV} mode`, {
11
+ url: `http://localhost:${PORT}`,
12
+ port: PORT,
13
+ });
14
+ });
15
+
16
+ // Graceful shutdown
17
+ const gracefulShutdown = (signal) => {
18
+ logger.warn(`${signal} signal received: closing HTTP server`);
19
+ server.close(() => {
20
+ logger.info("HTTP server closed");
21
+ process.exit(0);
22
+ });
23
+ };
24
+
25
+ process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
26
+ process.on("SIGINT", () => gracefulShutdown("SIGINT"));
27
+
28
+ // Unhandled promise rejections
29
+ process.on("unhandledRejection", (reason, promise) => {
30
+ logger.error("Unhandled Rejection at:", { promise, reason });
31
+ process.exit(1);
32
+ });
33
+
34
+ // Uncaught exceptions
35
+ process.on("uncaughtException", (error) => {
36
+ logger.error("Uncaught Exception:", { error: error.message });
37
+ process.exit(1);
38
+ });
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Operational Error Class
3
+ *
4
+ * Use for expected errors that can be handled gracefully
5
+ * Examples: validation errors, resource not found, auth failures
6
+ *
7
+ * These errors are logged and sent back to client as JSON
8
+ */
9
+ export class AppError extends Error {
10
+ constructor(
11
+ message,
12
+ statusCode = 500,
13
+ { isOperational = true, code = null, context = null, cause = null } = {},
14
+ ) {
15
+ super(message);
16
+
17
+ // Operational or Programmer error
18
+ this.isOperational = isOperational;
19
+
20
+ // HTTP status code
21
+ this.statusCode = statusCode;
22
+
23
+ // Error code for client handling (e.g., 'INVALID_EMAIL', 'USER_NOT_FOUND')
24
+ this.code = code;
25
+
26
+ // Additional context data
27
+ this.context = context || {};
28
+
29
+ // Original error that caused this
30
+ this.cause = cause;
31
+
32
+ // Timestamp
33
+ this.timestamp = new Date().toISOString();
34
+
35
+ // Preserve stack trace
36
+ Error.captureStackTrace(this, this.constructor);
37
+ }
38
+
39
+ /**
40
+ * Convert to JSON response format
41
+ */
42
+ toJSON() {
43
+ return {
44
+ success: false,
45
+ message: this.message,
46
+ code: this.code,
47
+ statusCode: this.statusCode,
48
+ ...(Object.keys(this.context).length > 0 && { context: this.context }),
49
+ timestamp: this.timestamp,
50
+ };
51
+ }
52
+
53
+ /**
54
+ * Get full error details for logging
55
+ */
56
+ getFullDetails() {
57
+ return {
58
+ message: this.message,
59
+ statusCode: this.statusCode,
60
+ code: this.code,
61
+ isOperational: this.isOperational,
62
+ context: this.context,
63
+ cause: this.cause?.message || null,
64
+ stack: this.stack,
65
+ timestamp: this.timestamp,
66
+ };
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Validation Error - extends AppError
72
+ * Use for input validation failures
73
+ */
74
+ export class ValidationError extends AppError {
75
+ constructor(message, errors = [], context = null) {
76
+ super(message, 422, {
77
+ isOperational: true,
78
+ code: "VALIDATION_ERROR",
79
+ context,
80
+ });
81
+ this.errors = errors;
82
+ this.name = "ValidationError";
83
+ }
84
+
85
+ toJSON() {
86
+ return {
87
+ ...super.toJSON(),
88
+ errors: this.errors,
89
+ };
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Authentication Error
95
+ * Use for auth/permission failures
96
+ */
97
+ export class AuthenticationError extends AppError {
98
+ constructor(message = "Unauthorized", context = null) {
99
+ super(message, 401, {
100
+ isOperational: true,
101
+ code: "AUTHENTICATION_ERROR",
102
+ context,
103
+ });
104
+ this.name = "AuthenticationError";
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Authorization Error
110
+ * Use for permission denied scenarios
111
+ */
112
+ export class AuthorizationError extends AppError {
113
+ constructor(message = "Forbidden", context = null) {
114
+ super(message, 403, {
115
+ isOperational: true,
116
+ code: "AUTHORIZATION_ERROR",
117
+ context,
118
+ });
119
+ this.name = "AuthorizationError";
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Not Found Error
125
+ * Use when resource doesn't exist
126
+ */
127
+ export class NotFoundError extends AppError {
128
+ constructor(resource = "Resource", context = null) {
129
+ super(`${resource} not found`, 404, {
130
+ isOperational: true,
131
+ code: "NOT_FOUND",
132
+ context,
133
+ });
134
+ this.name = "NotFoundError";
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Conflict Error
140
+ * Use for duplicate resources, business logic conflicts
141
+ */
142
+ export class ConflictError extends AppError {
143
+ constructor(message, context = null) {
144
+ super(message, 409, {
145
+ isOperational: true,
146
+ code: "CONFLICT",
147
+ context,
148
+ });
149
+ this.name = "ConflictError";
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Bad Request Error
155
+ * Use for malformed requests
156
+ */
157
+ export class BadRequestError extends AppError {
158
+ constructor(message, context = null) {
159
+ super(message, 400, {
160
+ isOperational: true,
161
+ code: "BAD_REQUEST",
162
+ context,
163
+ });
164
+ this.name = "BadRequestError";
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Internal Server Error
170
+ * Use for unexpected server-side errors (programmer errors)
171
+ */
172
+ export class InternalServerError extends AppError {
173
+ constructor(message = "Internal server error", cause = null, context = null) {
174
+ super(message, 500, {
175
+ isOperational: false,
176
+ code: "INTERNAL_SERVER_ERROR",
177
+ cause,
178
+ context,
179
+ });
180
+ this.name = "InternalServerError";
181
+ }
182
+ }