nexus-backend 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.
package/README.md ADDED
@@ -0,0 +1,288 @@
1
+ # Nexus Backend
2
+
3
+ A lightweight backend utility library for [Express.js](https://expressjs.com/) providing structured error classes, standardised API response helpers, and a plug-and-play error handling middleware.
4
+
5
+ ---
6
+
7
+ ## Table of Contents
8
+
9
+ - [Installation](#installation)
10
+ - [Quick Start](#quick-start)
11
+ - [API Reference](#api-reference)
12
+ - [Response Helpers](#response-helpers)
13
+ - [Error Classes](#error-classes)
14
+ - [Error Middleware](#error-middleware)
15
+ - [Response Shape](#response-shape)
16
+ - [TypeScript](#typescript)
17
+ - [License](#license)
18
+
19
+ ---
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ npm install nexus-backend
25
+ ```
26
+
27
+ Express is a peer dependency — make sure it is installed in your project:
28
+
29
+ ```bash
30
+ npm install express
31
+ ```
32
+
33
+ ---
34
+
35
+ ## Quick Start
36
+
37
+ ```ts
38
+ import express from "express";
39
+ import {
40
+ successResponse,
41
+ errorMiddleware,
42
+ NotFoundError,
43
+ ValidationError,
44
+ } from "nexusjs";
45
+
46
+ const app = express();
47
+ app.use(express.json());
48
+
49
+ // Example route
50
+ app.get("/users/:id", async (req, res, next) => {
51
+ try {
52
+ const user = await getUserById(req.params.id);
53
+
54
+ if (!user) {
55
+ throw new NotFoundError("User not found");
56
+ }
57
+
58
+ res.json(successResponse(user, "User fetched successfully"));
59
+ } catch (err) {
60
+ next(err);
61
+ }
62
+ });
63
+
64
+ // Register error middleware last
65
+ app.use(errorMiddleware);
66
+
67
+ app.listen(3000);
68
+ ```
69
+
70
+ ---
71
+
72
+ ## API Reference
73
+
74
+ ### Response Helpers
75
+
76
+ #### `successResponse(data, message?)`
77
+
78
+ Returns a structured success payload. Pass the result directly to `res.json()`.
79
+
80
+ ```ts
81
+ successResponse<T>(data: T, message?: string): SuccessResponse<T>
82
+ ```
83
+
84
+ **Example**
85
+
86
+ ```ts
87
+ res.status(200).json(
88
+ successResponse({ id: 1, name: "Alice" }, "User fetched successfully")
89
+ );
90
+ ```
91
+
92
+ ```json
93
+ {
94
+ "success": true,
95
+ "message": "User fetched successfully",
96
+ "data": { "id": 1, "name": "Alice" }
97
+ }
98
+ ```
99
+
100
+ ---
101
+
102
+ #### `errorResponse(message, errors?, stack?)`
103
+
104
+ Returns a structured error payload. You will rarely call this directly — `errorMiddleware` calls it internally. Useful if you need to construct an error response manually.
105
+
106
+ ```ts
107
+ errorResponse(message: string, errors?: any, stack?: string): ErrorResponse
108
+ ```
109
+
110
+ **Example**
111
+
112
+ ```ts
113
+ res.status(400).json(
114
+ errorResponse("Validation failed", { field: "email", issue: "Required" })
115
+ );
116
+ ```
117
+
118
+ ```json
119
+ {
120
+ "success": false,
121
+ "message": "Validation failed",
122
+ "errors": { "field": "email", "issue": "Required" }
123
+ }
124
+ ```
125
+
126
+ ---
127
+
128
+ ### Error Classes
129
+
130
+ All error classes extend the base `ApiError` class, which itself extends the native `Error`. Throw any of these inside a route and let `errorMiddleware` handle the rest.
131
+
132
+ #### `ApiError`
133
+
134
+ The base error class. Use this when none of the specific subclasses fit your use case.
135
+
136
+ ```ts
137
+ new ApiError(message: string, statusCode?: number, errors?: any, isOperational?: boolean)
138
+ ```
139
+
140
+ | Parameter | Type | Default | Description |
141
+ |---|---|---|---|
142
+ | `message` | `string` | — | Human-readable error message |
143
+ | `statusCode` | `number` | `500` | HTTP status code |
144
+ | `errors` | `any` | `undefined` | Additional error details or field errors |
145
+ | `isOperational` | `boolean` | `true` | Marks the error as an expected operational error |
146
+
147
+ ---
148
+
149
+ #### `BadRequestError`
150
+
151
+ **Status:** `400 Bad Request`
152
+
153
+ Use when the client sends a malformed or invalid request.
154
+
155
+ ```ts
156
+ throw new BadRequestError("Invalid request body");
157
+ ```
158
+
159
+ ---
160
+
161
+ #### `UnauthorizedError`
162
+
163
+ **Status:** `401 Unauthorized`
164
+
165
+ Use when authentication is missing or invalid.
166
+
167
+ ```ts
168
+ throw new UnauthorizedError("Invalid token");
169
+ ```
170
+
171
+ ---
172
+
173
+ #### `ForbiddenError`
174
+
175
+ **Status:** `403 Forbidden`
176
+
177
+ Use when an authenticated user lacks permission to access a resource.
178
+
179
+ ```ts
180
+ throw new ForbiddenError("You do not have access to this resource");
181
+ ```
182
+
183
+ ---
184
+
185
+ #### `NotFoundError`
186
+
187
+ **Status:** `404 Not Found`
188
+
189
+ Use when a requested resource does not exist.
190
+
191
+ ```ts
192
+ throw new NotFoundError("Post not found");
193
+ ```
194
+
195
+ ---
196
+
197
+ #### `ValidationError`
198
+
199
+ **Status:** `422 Unprocessable Entity`
200
+
201
+ Use when request data fails validation. Pass field-level errors via the `errors` argument.
202
+
203
+ ```ts
204
+ throw new ValidationError("Validation failed", [
205
+ { field: "email", message: "Must be a valid email address" },
206
+ { field: "password", message: "Must be at least 8 characters" },
207
+ ]);
208
+ ```
209
+
210
+ ---
211
+
212
+ ### Error Middleware
213
+
214
+ #### `errorMiddleware`
215
+
216
+ An Express-compatible error handling middleware. It catches any error passed to `next(err)`, determines the appropriate HTTP status code and message, and sends a structured `ErrorResponse`.
217
+
218
+ Register it **after all routes** and other middleware.
219
+
220
+ ```ts
221
+ import { errorMiddleware } from "nexusjs";
222
+
223
+ app.use(errorMiddleware);
224
+ ```
225
+
226
+ **Behaviour**
227
+
228
+ - If the error is an instance of `ApiError` (or any subclass), the middleware uses the error's own `statusCode` and `message`.
229
+ - For all other unhandled errors, it falls back to `500 Internal Server Error`.
230
+ - When `NODE_ENV` is set to `"development"`, the response includes a `stack` field with the full stack trace to aid debugging. The `stack` field is omitted in production.
231
+
232
+ **Development response example**
233
+
234
+ ```json
235
+ {
236
+ "success": false,
237
+ "message": "User not found",
238
+ "errors": null,
239
+ "stack": "NotFoundError: User not found\n at ..."
240
+ }
241
+ ```
242
+
243
+ ---
244
+
245
+ ## Response Shape
246
+
247
+ All responses follow a consistent structure.
248
+
249
+ #### Success
250
+
251
+ ```ts
252
+ interface SuccessResponse<T> {
253
+ success: true;
254
+ message?: string;
255
+ data: T;
256
+ }
257
+ ```
258
+
259
+ #### Error
260
+
261
+ ```ts
262
+ interface ErrorResponse {
263
+ success: false;
264
+ message: string;
265
+ errors?: any;
266
+ stack?: string; // only present in development
267
+ }
268
+ ```
269
+
270
+ ---
271
+
272
+ ## TypeScript
273
+
274
+ nexusjs is written in TypeScript and ships with type declarations out of the box. No `@types` package is needed.
275
+
276
+ `SuccessResponse` and `ErrorResponse` are exported and can be used to type your own response wrappers or API clients:
277
+
278
+ ```ts
279
+ import type { SuccessResponse, ErrorResponse } from "nexusjs";
280
+
281
+ type ApiResult<T> = SuccessResponse<T> | ErrorResponse;
282
+ ```
283
+
284
+ ---
285
+
286
+ ## License
287
+
288
+ MIT
@@ -0,0 +1,48 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+
3
+ interface SuccessResponse<T = any> {
4
+ success: true;
5
+ message?: string;
6
+ data: T;
7
+ }
8
+ interface ErrorResponse {
9
+ success: false;
10
+ message: string;
11
+ errors?: any;
12
+ stack?: string;
13
+ }
14
+
15
+ declare const successResponse: <T>(data: T, message?: string) => SuccessResponse<T>;
16
+
17
+ declare const errorResponse: (message: string, errors?: any, stack?: string) => ErrorResponse;
18
+
19
+ declare class ApiError extends Error {
20
+ statusCode: number;
21
+ isOperational: boolean;
22
+ errors?: any;
23
+ constructor(message: string, statusCode?: number, errors?: any, isOperational?: boolean);
24
+ }
25
+
26
+ declare class BadRequestError extends ApiError {
27
+ constructor(message?: string, errors?: any);
28
+ }
29
+
30
+ declare class UnauthorizedError extends ApiError {
31
+ constructor(message?: string, errors?: any);
32
+ }
33
+
34
+ declare class ForbiddenError extends ApiError {
35
+ constructor(message?: string, errors?: any);
36
+ }
37
+
38
+ declare class NotFoundError extends ApiError {
39
+ constructor(message?: string, errors?: any);
40
+ }
41
+
42
+ declare class ValidationError extends ApiError {
43
+ constructor(message?: string, errors?: any);
44
+ }
45
+
46
+ declare const errorHandler: (err: any, req: Request, res: Response, next: NextFunction) => Response<any, Record<string, any>>;
47
+
48
+ export { ApiError, BadRequestError, type ErrorResponse, ForbiddenError, NotFoundError, type SuccessResponse, UnauthorizedError, ValidationError, errorHandler as errorMiddleware, errorResponse, successResponse };
@@ -0,0 +1,48 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+
3
+ interface SuccessResponse<T = any> {
4
+ success: true;
5
+ message?: string;
6
+ data: T;
7
+ }
8
+ interface ErrorResponse {
9
+ success: false;
10
+ message: string;
11
+ errors?: any;
12
+ stack?: string;
13
+ }
14
+
15
+ declare const successResponse: <T>(data: T, message?: string) => SuccessResponse<T>;
16
+
17
+ declare const errorResponse: (message: string, errors?: any, stack?: string) => ErrorResponse;
18
+
19
+ declare class ApiError extends Error {
20
+ statusCode: number;
21
+ isOperational: boolean;
22
+ errors?: any;
23
+ constructor(message: string, statusCode?: number, errors?: any, isOperational?: boolean);
24
+ }
25
+
26
+ declare class BadRequestError extends ApiError {
27
+ constructor(message?: string, errors?: any);
28
+ }
29
+
30
+ declare class UnauthorizedError extends ApiError {
31
+ constructor(message?: string, errors?: any);
32
+ }
33
+
34
+ declare class ForbiddenError extends ApiError {
35
+ constructor(message?: string, errors?: any);
36
+ }
37
+
38
+ declare class NotFoundError extends ApiError {
39
+ constructor(message?: string, errors?: any);
40
+ }
41
+
42
+ declare class ValidationError extends ApiError {
43
+ constructor(message?: string, errors?: any);
44
+ }
45
+
46
+ declare const errorHandler: (err: any, req: Request, res: Response, next: NextFunction) => Response<any, Record<string, any>>;
47
+
48
+ export { ApiError, BadRequestError, type ErrorResponse, ForbiddenError, NotFoundError, type SuccessResponse, UnauthorizedError, ValidationError, errorHandler as errorMiddleware, errorResponse, successResponse };
package/dist/index.js ADDED
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ApiError: () => ApiError,
24
+ BadRequestError: () => BadRequestError,
25
+ ForbiddenError: () => ForbiddenError,
26
+ NotFoundError: () => NotFoundError,
27
+ UnauthorizedError: () => UnauthorizedError,
28
+ ValidationError: () => ValidationError,
29
+ errorMiddleware: () => errorHandler_default,
30
+ errorResponse: () => errorResponse,
31
+ successResponse: () => successResponse
32
+ });
33
+ module.exports = __toCommonJS(index_exports);
34
+
35
+ // src/responses/successResponse.ts
36
+ var successResponse = (data, message) => ({
37
+ success: true,
38
+ data,
39
+ message
40
+ });
41
+
42
+ // src/responses/errorResponse.ts
43
+ var errorResponse = (message, errors, stack) => ({
44
+ success: false,
45
+ message,
46
+ errors,
47
+ stack
48
+ });
49
+
50
+ // src/errors/ApiError.ts
51
+ var ApiError = class extends Error {
52
+ constructor(message, statusCode = 500, errors, isOperational = true) {
53
+ super(message);
54
+ this.statusCode = statusCode;
55
+ this.errors = errors;
56
+ this.isOperational = isOperational;
57
+ Error.captureStackTrace(this, this.constructor);
58
+ }
59
+ };
60
+
61
+ // src/errors/BadRequestError.ts
62
+ var BadRequestError = class extends ApiError {
63
+ constructor(message = "Bad Request", errors) {
64
+ super(message, 400, errors);
65
+ }
66
+ };
67
+
68
+ // src/errors/UnauthorisedError.ts
69
+ var UnauthorizedError = class extends ApiError {
70
+ constructor(message = "Unauthorized", errors) {
71
+ super(message, 401, errors);
72
+ }
73
+ };
74
+
75
+ // src/errors/ForbiddenError.ts
76
+ var ForbiddenError = class extends ApiError {
77
+ constructor(message = "Forbidden", errors) {
78
+ super(message, 403, errors);
79
+ }
80
+ };
81
+
82
+ // src/errors/NotFoundError.ts
83
+ var NotFoundError = class extends ApiError {
84
+ constructor(message = "Resource Not Found", errors) {
85
+ super(message, 404, errors);
86
+ }
87
+ };
88
+
89
+ // src/errors/ValidationError.ts
90
+ var ValidationError = class extends ApiError {
91
+ constructor(message = "Validation Failed", errors) {
92
+ super(message, 422, errors);
93
+ }
94
+ };
95
+
96
+ // src/handlers/errorHandler.ts
97
+ var errorHandler = (err, req, res, next) => {
98
+ console.error("Error:", err);
99
+ let statusCode = 500;
100
+ let message = "Internal Server Error";
101
+ let errors = void 0;
102
+ let stack = void 0;
103
+ if (err instanceof ApiError) {
104
+ statusCode = err.statusCode;
105
+ message = err.message;
106
+ errors = err.errors;
107
+ }
108
+ if (process.env.NODE_ENV === "development") {
109
+ stack = err.stack;
110
+ }
111
+ return res.status(statusCode).json(
112
+ errorResponse(
113
+ message,
114
+ errors,
115
+ stack
116
+ )
117
+ );
118
+ };
119
+ var errorHandler_default = errorHandler;
120
+ // Annotate the CommonJS export names for ESM import in node:
121
+ 0 && (module.exports = {
122
+ ApiError,
123
+ BadRequestError,
124
+ ForbiddenError,
125
+ NotFoundError,
126
+ UnauthorizedError,
127
+ ValidationError,
128
+ errorMiddleware,
129
+ errorResponse,
130
+ successResponse
131
+ });
132
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/responses/successResponse.ts","../src/responses/errorResponse.ts","../src/errors/ApiError.ts","../src/errors/BadRequestError.ts","../src/errors/UnauthorisedError.ts","../src/errors/ForbiddenError.ts","../src/errors/NotFoundError.ts","../src/errors/ValidationError.ts","../src/handlers/errorHandler.ts"],"sourcesContent":["export { successResponse } from \"./responses/successResponse\";\r\nexport { errorResponse } from \"./responses/errorResponse\";\r\n\r\nexport { default as ApiError } from \"./errors/ApiError\";\r\nexport { default as BadRequestError } from \"./errors/BadRequestError\";\r\nexport { default as UnauthorizedError } from \"./errors/UnauthorisedError\";\r\nexport { default as ForbiddenError } from \"./errors/ForbiddenError\";\r\nexport { default as NotFoundError } from \"./errors/NotFoundError\";\r\nexport { default as ValidationError } from \"./errors/ValidationError\";\r\n\r\nexport { default as errorMiddleware } from \"./handlers/errorHandler\";\r\n\r\nexport type {\r\n SuccessResponse,\r\n ErrorResponse,\r\n} from \"./types/response.types\";","import { SuccessResponse } from \"../types/response.types\";\r\n\r\nexport const successResponse = <T>(\r\n data: T,\r\n message?: string\r\n): SuccessResponse<T> => ({\r\n success: true,\r\n data,\r\n message,\r\n});","import { ErrorResponse } from \"../types/response.types\";\r\n\r\nexport const errorResponse = (\r\n message: string,\r\n errors?: any,\r\n stack?: string\r\n): ErrorResponse => ({\r\n success: false,\r\n message,\r\n errors,\r\n stack,\r\n});","export default class ApiError extends Error {\r\n statusCode: number;\r\n isOperational: boolean;\r\n errors?: any;\r\n\r\n constructor(\r\n message: string,\r\n statusCode = 500,\r\n errors?: any,\r\n isOperational = true\r\n ) {\r\n super(message);\r\n\r\n this.statusCode = statusCode;\r\n this.errors = errors;\r\n this.isOperational = isOperational;\r\n\r\n Error.captureStackTrace(this, this.constructor);\r\n }\r\n}","import ApiError from \"./ApiError\";\r\n\r\nexport default class BadRequestError extends ApiError {\r\n constructor(message = \"Bad Request\", errors?: any) {\r\n super(message, 400, errors);\r\n }\r\n}","import ApiError from \"./ApiError\";\r\n\r\nexport default class UnauthorizedError extends ApiError {\r\n constructor(message = \"Unauthorized\", errors?: any) {\r\n super(message, 401, errors);\r\n }\r\n}","import ApiError from \"./ApiError\";\r\n\r\nexport default class ForbiddenError extends ApiError {\r\n constructor(message = \"Forbidden\", errors?: any) {\r\n super(message, 403, errors);\r\n }\r\n}","import ApiError from \"./ApiError\";\r\n\r\nexport default class NotFoundError extends ApiError {\r\n constructor(message = \"Resource Not Found\", errors?: any) {\r\n super(message, 404, errors);\r\n }\r\n}","import ApiError from \"./ApiError\";\r\n\r\nexport default class ValidationError extends ApiError {\r\n constructor(message = \"Validation Failed\", errors?: any) {\r\n super(message, 422, errors);\r\n }\r\n}","import { Request, Response, NextFunction } from \"express\";\r\n\r\nimport ApiError from \"../errors/ApiError\";\r\nimport { errorResponse } from \"../responses/errorResponse\";\r\n\r\nconst errorHandler = (\r\n err: any,\r\n req: Request,\r\n res: Response,\r\n next: NextFunction\r\n) => {\r\n\r\n console.error(\"Error:\", err);\r\n\r\n let statusCode = 500;\r\n let message = \"Internal Server Error\";\r\n let errors = undefined;\r\n let stack = undefined;\r\n\r\n // Custom application errors\r\n if (err instanceof ApiError) {\r\n statusCode = err.statusCode;\r\n message = err.message;\r\n errors = err.errors;\r\n }\r\n\r\n // Development stack trace\r\n if (process.env.NODE_ENV === \"development\") {\r\n stack = err.stack;\r\n }\r\n\r\n return res.status(statusCode).json(\r\n errorResponse(\r\n message,\r\n errors,\r\n stack\r\n )\r\n );\r\n};\r\n\r\nexport default errorHandler;"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,kBAAkB,CAC7B,MACA,aACwB;AAAA,EACxB,SAAS;AAAA,EACT;AAAA,EACA;AACF;;;ACPO,IAAM,gBAAgB,CAC3B,SACA,QACA,WACmB;AAAA,EACnB,SAAS;AAAA,EACT;AAAA,EACA;AAAA,EACA;AACF;;;ACXA,IAAqB,WAArB,cAAsC,MAAM;AAAA,EAK1C,YACE,SACA,aAAa,KACb,QACA,gBAAgB,MAChB;AACA,UAAM,OAAO;AAEb,SAAK,aAAa;AAClB,SAAK,SAAS;AACd,SAAK,gBAAgB;AAErB,UAAM,kBAAkB,MAAM,KAAK,WAAW;AAAA,EAChD;AACF;;;ACjBA,IAAqB,kBAArB,cAA6C,SAAS;AAAA,EACpD,YAAY,UAAU,eAAe,QAAc;AACjD,UAAM,SAAS,KAAK,MAAM;AAAA,EAC5B;AACF;;;ACJA,IAAqB,oBAArB,cAA+C,SAAS;AAAA,EACtD,YAAY,UAAU,gBAAgB,QAAc;AAClD,UAAM,SAAS,KAAK,MAAM;AAAA,EAC5B;AACF;;;ACJA,IAAqB,iBAArB,cAA4C,SAAS;AAAA,EACnD,YAAY,UAAU,aAAa,QAAc;AAC/C,UAAM,SAAS,KAAK,MAAM;AAAA,EAC5B;AACF;;;ACJA,IAAqB,gBAArB,cAA2C,SAAS;AAAA,EAClD,YAAY,UAAU,sBAAsB,QAAc;AACxD,UAAM,SAAS,KAAK,MAAM;AAAA,EAC5B;AACF;;;ACJA,IAAqB,kBAArB,cAA6C,SAAS;AAAA,EACpD,YAAY,UAAU,qBAAqB,QAAc;AACvD,UAAM,SAAS,KAAK,MAAM;AAAA,EAC5B;AACF;;;ACDA,IAAM,eAAe,CACnB,KACA,KACA,KACA,SACG;AAEH,UAAQ,MAAM,UAAU,GAAG;AAE3B,MAAI,aAAa;AACjB,MAAI,UAAU;AACd,MAAI,SAAS;AACb,MAAI,QAAQ;AAGZ,MAAI,eAAe,UAAU;AAC3B,iBAAa,IAAI;AACjB,cAAU,IAAI;AACd,aAAS,IAAI;AAAA,EACf;AAGA,MAAI,QAAQ,IAAI,aAAa,eAAe;AAC1C,YAAQ,IAAI;AAAA,EACd;AAEA,SAAO,IAAI,OAAO,UAAU,EAAE;AAAA,IAC5B;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,uBAAQ;","names":[]}
package/dist/index.mjs ADDED
@@ -0,0 +1,97 @@
1
+ // src/responses/successResponse.ts
2
+ var successResponse = (data, message) => ({
3
+ success: true,
4
+ data,
5
+ message
6
+ });
7
+
8
+ // src/responses/errorResponse.ts
9
+ var errorResponse = (message, errors, stack) => ({
10
+ success: false,
11
+ message,
12
+ errors,
13
+ stack
14
+ });
15
+
16
+ // src/errors/ApiError.ts
17
+ var ApiError = class extends Error {
18
+ constructor(message, statusCode = 500, errors, isOperational = true) {
19
+ super(message);
20
+ this.statusCode = statusCode;
21
+ this.errors = errors;
22
+ this.isOperational = isOperational;
23
+ Error.captureStackTrace(this, this.constructor);
24
+ }
25
+ };
26
+
27
+ // src/errors/BadRequestError.ts
28
+ var BadRequestError = class extends ApiError {
29
+ constructor(message = "Bad Request", errors) {
30
+ super(message, 400, errors);
31
+ }
32
+ };
33
+
34
+ // src/errors/UnauthorisedError.ts
35
+ var UnauthorizedError = class extends ApiError {
36
+ constructor(message = "Unauthorized", errors) {
37
+ super(message, 401, errors);
38
+ }
39
+ };
40
+
41
+ // src/errors/ForbiddenError.ts
42
+ var ForbiddenError = class extends ApiError {
43
+ constructor(message = "Forbidden", errors) {
44
+ super(message, 403, errors);
45
+ }
46
+ };
47
+
48
+ // src/errors/NotFoundError.ts
49
+ var NotFoundError = class extends ApiError {
50
+ constructor(message = "Resource Not Found", errors) {
51
+ super(message, 404, errors);
52
+ }
53
+ };
54
+
55
+ // src/errors/ValidationError.ts
56
+ var ValidationError = class extends ApiError {
57
+ constructor(message = "Validation Failed", errors) {
58
+ super(message, 422, errors);
59
+ }
60
+ };
61
+
62
+ // src/handlers/errorHandler.ts
63
+ var errorHandler = (err, req, res, next) => {
64
+ console.error("Error:", err);
65
+ let statusCode = 500;
66
+ let message = "Internal Server Error";
67
+ let errors = void 0;
68
+ let stack = void 0;
69
+ if (err instanceof ApiError) {
70
+ statusCode = err.statusCode;
71
+ message = err.message;
72
+ errors = err.errors;
73
+ }
74
+ if (process.env.NODE_ENV === "development") {
75
+ stack = err.stack;
76
+ }
77
+ return res.status(statusCode).json(
78
+ errorResponse(
79
+ message,
80
+ errors,
81
+ stack
82
+ )
83
+ );
84
+ };
85
+ var errorHandler_default = errorHandler;
86
+ export {
87
+ ApiError,
88
+ BadRequestError,
89
+ ForbiddenError,
90
+ NotFoundError,
91
+ UnauthorizedError,
92
+ ValidationError,
93
+ errorHandler_default as errorMiddleware,
94
+ errorResponse,
95
+ successResponse
96
+ };
97
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/responses/successResponse.ts","../src/responses/errorResponse.ts","../src/errors/ApiError.ts","../src/errors/BadRequestError.ts","../src/errors/UnauthorisedError.ts","../src/errors/ForbiddenError.ts","../src/errors/NotFoundError.ts","../src/errors/ValidationError.ts","../src/handlers/errorHandler.ts"],"sourcesContent":["import { SuccessResponse } from \"../types/response.types\";\r\n\r\nexport const successResponse = <T>(\r\n data: T,\r\n message?: string\r\n): SuccessResponse<T> => ({\r\n success: true,\r\n data,\r\n message,\r\n});","import { ErrorResponse } from \"../types/response.types\";\r\n\r\nexport const errorResponse = (\r\n message: string,\r\n errors?: any,\r\n stack?: string\r\n): ErrorResponse => ({\r\n success: false,\r\n message,\r\n errors,\r\n stack,\r\n});","export default class ApiError extends Error {\r\n statusCode: number;\r\n isOperational: boolean;\r\n errors?: any;\r\n\r\n constructor(\r\n message: string,\r\n statusCode = 500,\r\n errors?: any,\r\n isOperational = true\r\n ) {\r\n super(message);\r\n\r\n this.statusCode = statusCode;\r\n this.errors = errors;\r\n this.isOperational = isOperational;\r\n\r\n Error.captureStackTrace(this, this.constructor);\r\n }\r\n}","import ApiError from \"./ApiError\";\r\n\r\nexport default class BadRequestError extends ApiError {\r\n constructor(message = \"Bad Request\", errors?: any) {\r\n super(message, 400, errors);\r\n }\r\n}","import ApiError from \"./ApiError\";\r\n\r\nexport default class UnauthorizedError extends ApiError {\r\n constructor(message = \"Unauthorized\", errors?: any) {\r\n super(message, 401, errors);\r\n }\r\n}","import ApiError from \"./ApiError\";\r\n\r\nexport default class ForbiddenError extends ApiError {\r\n constructor(message = \"Forbidden\", errors?: any) {\r\n super(message, 403, errors);\r\n }\r\n}","import ApiError from \"./ApiError\";\r\n\r\nexport default class NotFoundError extends ApiError {\r\n constructor(message = \"Resource Not Found\", errors?: any) {\r\n super(message, 404, errors);\r\n }\r\n}","import ApiError from \"./ApiError\";\r\n\r\nexport default class ValidationError extends ApiError {\r\n constructor(message = \"Validation Failed\", errors?: any) {\r\n super(message, 422, errors);\r\n }\r\n}","import { Request, Response, NextFunction } from \"express\";\r\n\r\nimport ApiError from \"../errors/ApiError\";\r\nimport { errorResponse } from \"../responses/errorResponse\";\r\n\r\nconst errorHandler = (\r\n err: any,\r\n req: Request,\r\n res: Response,\r\n next: NextFunction\r\n) => {\r\n\r\n console.error(\"Error:\", err);\r\n\r\n let statusCode = 500;\r\n let message = \"Internal Server Error\";\r\n let errors = undefined;\r\n let stack = undefined;\r\n\r\n // Custom application errors\r\n if (err instanceof ApiError) {\r\n statusCode = err.statusCode;\r\n message = err.message;\r\n errors = err.errors;\r\n }\r\n\r\n // Development stack trace\r\n if (process.env.NODE_ENV === \"development\") {\r\n stack = err.stack;\r\n }\r\n\r\n return res.status(statusCode).json(\r\n errorResponse(\r\n message,\r\n errors,\r\n stack\r\n )\r\n );\r\n};\r\n\r\nexport default errorHandler;"],"mappings":";AAEO,IAAM,kBAAkB,CAC7B,MACA,aACwB;AAAA,EACxB,SAAS;AAAA,EACT;AAAA,EACA;AACF;;;ACPO,IAAM,gBAAgB,CAC3B,SACA,QACA,WACmB;AAAA,EACnB,SAAS;AAAA,EACT;AAAA,EACA;AAAA,EACA;AACF;;;ACXA,IAAqB,WAArB,cAAsC,MAAM;AAAA,EAK1C,YACE,SACA,aAAa,KACb,QACA,gBAAgB,MAChB;AACA,UAAM,OAAO;AAEb,SAAK,aAAa;AAClB,SAAK,SAAS;AACd,SAAK,gBAAgB;AAErB,UAAM,kBAAkB,MAAM,KAAK,WAAW;AAAA,EAChD;AACF;;;ACjBA,IAAqB,kBAArB,cAA6C,SAAS;AAAA,EACpD,YAAY,UAAU,eAAe,QAAc;AACjD,UAAM,SAAS,KAAK,MAAM;AAAA,EAC5B;AACF;;;ACJA,IAAqB,oBAArB,cAA+C,SAAS;AAAA,EACtD,YAAY,UAAU,gBAAgB,QAAc;AAClD,UAAM,SAAS,KAAK,MAAM;AAAA,EAC5B;AACF;;;ACJA,IAAqB,iBAArB,cAA4C,SAAS;AAAA,EACnD,YAAY,UAAU,aAAa,QAAc;AAC/C,UAAM,SAAS,KAAK,MAAM;AAAA,EAC5B;AACF;;;ACJA,IAAqB,gBAArB,cAA2C,SAAS;AAAA,EAClD,YAAY,UAAU,sBAAsB,QAAc;AACxD,UAAM,SAAS,KAAK,MAAM;AAAA,EAC5B;AACF;;;ACJA,IAAqB,kBAArB,cAA6C,SAAS;AAAA,EACpD,YAAY,UAAU,qBAAqB,QAAc;AACvD,UAAM,SAAS,KAAK,MAAM;AAAA,EAC5B;AACF;;;ACDA,IAAM,eAAe,CACnB,KACA,KACA,KACA,SACG;AAEH,UAAQ,MAAM,UAAU,GAAG;AAE3B,MAAI,aAAa;AACjB,MAAI,UAAU;AACd,MAAI,SAAS;AACb,MAAI,QAAQ;AAGZ,MAAI,eAAe,UAAU;AAC3B,iBAAa,IAAI;AACjB,cAAU,IAAI;AACd,aAAS,IAAI;AAAA,EACf;AAGA,MAAI,QAAQ,IAAI,aAAa,eAAe;AAC1C,YAAQ,IAAI;AAAA,EACd;AAEA,SAAO,IAAI,OAAO,UAAU,EAAE;AAAA,IAC5B;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,uBAAQ;","names":[]}
package/package.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "nexus-backend",
3
+ "version": "1.0.0",
4
+ "description": "Backend utility library for Express.js",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "scripts": {
12
+ "build": "tsup"
13
+ },
14
+ "peerDependencies": {
15
+ "express": "^5.0.6"
16
+ },
17
+ "devDependencies": {
18
+ "@types/express": "^5.0.6",
19
+ "tsup": "^8.5.1",
20
+ "typescript": "^5.8.3"
21
+ }
22
+ }