nexus-backend 1.0.1 → 1.0.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/README.md +92 -31
- package/dist/index.d.mts +13 -1
- package/dist/index.d.ts +13 -1
- package/dist/index.js +47 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +35 -0
- package/dist/index.mjs.map +1 -1
- package/package.json +12 -3
package/README.md
CHANGED
|
@@ -21,13 +21,14 @@ A lightweight backend utility library for [Express.js](https://expressjs.com/) p
|
|
|
21
21
|
## Installation
|
|
22
22
|
|
|
23
23
|
```bash
|
|
24
|
-
|
|
24
|
+
|
|
25
|
+
npm install express mongoose cors helmet morgan cookie-parser
|
|
25
26
|
```
|
|
26
27
|
|
|
27
|
-
Express
|
|
28
|
+
Express, mongoose, cors, helmet, morgan, and cookie-parser are peer dependencies — make sure they are installed in your project:
|
|
28
29
|
|
|
29
30
|
```bash
|
|
30
|
-
npm install
|
|
31
|
+
npm install nexus-backend
|
|
31
32
|
```
|
|
32
33
|
|
|
33
34
|
---
|
|
@@ -35,39 +36,97 @@ npm install express
|
|
|
35
36
|
## Quick Start
|
|
36
37
|
|
|
37
38
|
```ts
|
|
38
|
-
|
|
39
|
+
// src/config/mongoConfig.ts
|
|
40
|
+
import { type MongoConfig } from "nexus-backend";
|
|
41
|
+
|
|
42
|
+
const dbConfig: MongoConfig = {
|
|
43
|
+
subDomain: requiredEnv(process.env.DB_HOST, "DB_HOST"),
|
|
44
|
+
userName: requiredEnv(process.env.DB_USERNAME, "DB_USERNAME"),
|
|
45
|
+
password: requiredEnv(process.env.DB_PASSWORD, "DB_PASSWORD"),
|
|
46
|
+
cluster: requiredEnv(process.env.DB_CLUSTER, "DB_CLUSTER"),
|
|
47
|
+
dbName: requiredEnv(process.env.DB_NAME, "DB_NAME"),
|
|
48
|
+
};
|
|
49
|
+
export default dbConfig;
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
// src/server.ts
|
|
54
|
+
import express, { type Application, Request, Response } from "express";
|
|
55
|
+
import http from "http";
|
|
39
56
|
import {
|
|
40
57
|
successResponse,
|
|
41
58
|
errorMiddleware,
|
|
42
59
|
NotFoundError,
|
|
43
60
|
ValidationError,
|
|
44
61
|
} from "nexus-backend";
|
|
62
|
+
import cors from "cors";
|
|
63
|
+
import helmet from "helmet";
|
|
64
|
+
import morgan from "morgan";
|
|
65
|
+
import cookieParser from "cookie-parser";
|
|
66
|
+
import { Server } from "socket.io";
|
|
45
67
|
|
|
46
|
-
const app = express();
|
|
47
|
-
app.use(express.json());
|
|
68
|
+
const app: Application = express();
|
|
48
69
|
|
|
49
|
-
|
|
50
|
-
app.
|
|
51
|
-
|
|
52
|
-
|
|
70
|
+
if (process.env.NODE_ENV !== "production") {
|
|
71
|
+
app.use(morgan("dev"));
|
|
72
|
+
}
|
|
73
|
+
app.set("trust proxy", 1);
|
|
74
|
+
app.use(helmet());
|
|
75
|
+
app.use(
|
|
76
|
+
cors({
|
|
77
|
+
origin: process.env.FRONTEND_URL,
|
|
78
|
+
credentials: true,
|
|
79
|
+
}),
|
|
80
|
+
);
|
|
53
81
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
82
|
+
app.use(express.json({ limit: "500mb" })); // Adjust the limit as needed
|
|
83
|
+
app.use(express.urlencoded({ extended: true, limit: "500mb" })); // For parsing application/x-www-form-urlencoded
|
|
84
|
+
app.use(cookieParser());
|
|
57
85
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
86
|
+
// Example route
|
|
87
|
+
app.get("/users/:id", async (req: Request, res: Response) => {
|
|
88
|
+
const user = await getUserById(req.params.id);
|
|
89
|
+
|
|
90
|
+
if (!user) {
|
|
91
|
+
throw new NotFoundError("User not found");
|
|
61
92
|
}
|
|
93
|
+
|
|
94
|
+
res.json(successResponse(user, "User fetched successfully"));
|
|
62
95
|
});
|
|
63
96
|
|
|
64
97
|
// Register error middleware last
|
|
65
98
|
app.use(errorMiddleware);
|
|
99
|
+
const server = http.createServer(app);
|
|
100
|
+
export const io = new Server(server, {
|
|
101
|
+
cors: {
|
|
102
|
+
origin: process.env.FRONTEND_URL,
|
|
103
|
+
credentials: true,
|
|
104
|
+
},
|
|
105
|
+
});
|
|
66
106
|
|
|
67
|
-
|
|
107
|
+
export default server;
|
|
68
108
|
```
|
|
69
109
|
|
|
70
|
-
|
|
110
|
+
```ts
|
|
111
|
+
// src/index.ts
|
|
112
|
+
import "dotenv/config";
|
|
113
|
+
import { connectMongoDb } from "nexus-backend";
|
|
114
|
+
import dns from "dns";
|
|
115
|
+
import dbConfig from "./config/mongoConfig";
|
|
116
|
+
import server from "./server";
|
|
117
|
+
const PORT = process.env.PORT || 5000;
|
|
118
|
+
async () => {
|
|
119
|
+
dns.setServers(["1.1.1.1", "1.0.0.1"]);
|
|
120
|
+
const dbConnected = await connectMongoDb(dbConfig);
|
|
121
|
+
if (!dbConnected) {
|
|
122
|
+
console.error("Database connection failed. Exiting...");
|
|
123
|
+
process.exit(1);
|
|
124
|
+
}
|
|
125
|
+
server.listen(PORT, () => {
|
|
126
|
+
console.log(`Server running on ${PORT}`);
|
|
127
|
+
});
|
|
128
|
+
};
|
|
129
|
+
```
|
|
71
130
|
|
|
72
131
|
## API Reference
|
|
73
132
|
|
|
@@ -84,9 +143,9 @@ successResponse<T>(data: T, message?: string): SuccessResponse<T>
|
|
|
84
143
|
**Example**
|
|
85
144
|
|
|
86
145
|
```ts
|
|
87
|
-
res
|
|
88
|
-
|
|
89
|
-
);
|
|
146
|
+
res
|
|
147
|
+
.status(200)
|
|
148
|
+
.json(successResponse({ id: 1, name: "Alice" }, "User fetched successfully"));
|
|
90
149
|
```
|
|
91
150
|
|
|
92
151
|
```json
|
|
@@ -110,9 +169,11 @@ errorResponse(message: string, errors?: any, stack?: string): ErrorResponse
|
|
|
110
169
|
**Example**
|
|
111
170
|
|
|
112
171
|
```ts
|
|
113
|
-
res
|
|
114
|
-
|
|
115
|
-
|
|
172
|
+
res
|
|
173
|
+
.status(400)
|
|
174
|
+
.json(
|
|
175
|
+
errorResponse("Validation failed", { field: "email", issue: "Required" }),
|
|
176
|
+
);
|
|
116
177
|
```
|
|
117
178
|
|
|
118
179
|
```json
|
|
@@ -137,12 +198,12 @@ The base error class. Use this when none of the specific subclasses fit your use
|
|
|
137
198
|
new ApiError(message: string, statusCode?: number, errors?: any, isOperational?: boolean)
|
|
138
199
|
```
|
|
139
200
|
|
|
140
|
-
| Parameter
|
|
141
|
-
|
|
142
|
-
| `message`
|
|
143
|
-
| `statusCode`
|
|
144
|
-
| `errors`
|
|
145
|
-
| `isOperational` | `boolean` | `true`
|
|
201
|
+
| Parameter | Type | Default | Description |
|
|
202
|
+
| --------------- | --------- | ----------- | ------------------------------------------------ |
|
|
203
|
+
| `message` | `string` | — | Human-readable error message |
|
|
204
|
+
| `statusCode` | `number` | `500` | HTTP status code |
|
|
205
|
+
| `errors` | `any` | `undefined` | Additional error details or field errors |
|
|
206
|
+
| `isOperational` | `boolean` | `true` | Marks the error as an expected operational error |
|
|
146
207
|
|
|
147
208
|
---
|
|
148
209
|
|
|
@@ -285,4 +346,4 @@ type ApiResult<T> = SuccessResponse<T> | ErrorResponse;
|
|
|
285
346
|
|
|
286
347
|
## License
|
|
287
348
|
|
|
288
|
-
MIT
|
|
349
|
+
MIT
|
package/dist/index.d.mts
CHANGED
|
@@ -16,6 +16,18 @@ declare const successResponse: <T>(data: T, message?: string) => SuccessResponse
|
|
|
16
16
|
|
|
17
17
|
declare const errorResponse: (message: string, errors?: any, stack?: string) => ErrorResponse;
|
|
18
18
|
|
|
19
|
+
declare const requiredEnv: (value: string | undefined, key: string) => string;
|
|
20
|
+
|
|
21
|
+
interface MongoConfig {
|
|
22
|
+
subDomain: string;
|
|
23
|
+
userName: string;
|
|
24
|
+
password: string;
|
|
25
|
+
cluster: string;
|
|
26
|
+
dbName: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
declare const connectMongoDb: (config: MongoConfig) => Promise<boolean>;
|
|
30
|
+
|
|
19
31
|
declare class ApiError extends Error {
|
|
20
32
|
statusCode: number;
|
|
21
33
|
isOperational: boolean;
|
|
@@ -48,4 +60,4 @@ declare const errorHandler: [
|
|
|
48
60
|
(err: any, req: Request, res: Response, next: NextFunction) => void
|
|
49
61
|
];
|
|
50
62
|
|
|
51
|
-
export { ApiError, BadRequestError, type ErrorResponse, ForbiddenError, NotFoundError, type SuccessResponse, UnauthorizedError, ValidationError, errorHandler as errorMiddleware, errorResponse, successResponse };
|
|
63
|
+
export { ApiError, BadRequestError, type ErrorResponse, ForbiddenError, type MongoConfig, NotFoundError, type SuccessResponse, UnauthorizedError, ValidationError, connectMongoDb, errorHandler as errorMiddleware, errorResponse, requiredEnv, successResponse };
|
package/dist/index.d.ts
CHANGED
|
@@ -16,6 +16,18 @@ declare const successResponse: <T>(data: T, message?: string) => SuccessResponse
|
|
|
16
16
|
|
|
17
17
|
declare const errorResponse: (message: string, errors?: any, stack?: string) => ErrorResponse;
|
|
18
18
|
|
|
19
|
+
declare const requiredEnv: (value: string | undefined, key: string) => string;
|
|
20
|
+
|
|
21
|
+
interface MongoConfig {
|
|
22
|
+
subDomain: string;
|
|
23
|
+
userName: string;
|
|
24
|
+
password: string;
|
|
25
|
+
cluster: string;
|
|
26
|
+
dbName: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
declare const connectMongoDb: (config: MongoConfig) => Promise<boolean>;
|
|
30
|
+
|
|
19
31
|
declare class ApiError extends Error {
|
|
20
32
|
statusCode: number;
|
|
21
33
|
isOperational: boolean;
|
|
@@ -48,4 +60,4 @@ declare const errorHandler: [
|
|
|
48
60
|
(err: any, req: Request, res: Response, next: NextFunction) => void
|
|
49
61
|
];
|
|
50
62
|
|
|
51
|
-
export { ApiError, BadRequestError, type ErrorResponse, ForbiddenError, NotFoundError, type SuccessResponse, UnauthorizedError, ValidationError, errorHandler as errorMiddleware, errorResponse, successResponse };
|
|
63
|
+
export { ApiError, BadRequestError, type ErrorResponse, ForbiddenError, type MongoConfig, NotFoundError, type SuccessResponse, UnauthorizedError, ValidationError, connectMongoDb, errorHandler as errorMiddleware, errorResponse, requiredEnv, successResponse };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
8
|
var __export = (target, all) => {
|
|
7
9
|
for (var name in all)
|
|
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
17
|
}
|
|
16
18
|
return to;
|
|
17
19
|
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
18
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
29
|
|
|
20
30
|
// src/index.ts
|
|
@@ -26,8 +36,10 @@ __export(index_exports, {
|
|
|
26
36
|
NotFoundError: () => NotFoundError,
|
|
27
37
|
UnauthorizedError: () => UnauthorizedError,
|
|
28
38
|
ValidationError: () => ValidationError,
|
|
39
|
+
connectMongoDb: () => connectMongoDb,
|
|
29
40
|
errorMiddleware: () => errorHandler_default,
|
|
30
41
|
errorResponse: () => errorResponse,
|
|
42
|
+
requiredEnv: () => requiredEnv,
|
|
31
43
|
successResponse: () => successResponse
|
|
32
44
|
});
|
|
33
45
|
module.exports = __toCommonJS(index_exports);
|
|
@@ -47,6 +59,39 @@ var errorResponse = (message, errors, stack) => ({
|
|
|
47
59
|
stack
|
|
48
60
|
});
|
|
49
61
|
|
|
62
|
+
// src/utils/envManager.ts
|
|
63
|
+
var requiredEnv = (value, key) => {
|
|
64
|
+
if (!value) {
|
|
65
|
+
throw new Error(`Missing required environment variable: ${key}`);
|
|
66
|
+
}
|
|
67
|
+
return value;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
// src/config/mongoConfig.ts
|
|
71
|
+
var import_mongoose = __toESM(require("mongoose"));
|
|
72
|
+
var connectMongoDb = async (config) => {
|
|
73
|
+
const { subDomain, userName, password, cluster, dbName } = config;
|
|
74
|
+
const srvURL = `mongodb+srv://${userName}:${password}@${cluster.toLowerCase()}.${subDomain}.mongodb.net/${dbName}?retryWrites=true&w=majority&appName=${cluster.toLowerCase()}`;
|
|
75
|
+
const fallbackURL = `mongodb://${userName}:${password}@ac-hkntio7-shard-00-00.${subDomain}.mongodb.net:27017,ac-hkntio7-shard-00-01.${subDomain}.mongodb.net:27017,ac-hkntio7-shard-00-02.${subDomain}.mongodb.net:27017/${dbName}?ssl=true&replicaSet=atlas-cji6jk-shard-0&authSource=admin&appName=${cluster}`;
|
|
76
|
+
try {
|
|
77
|
+
console.log("Trying primary +srv connection...");
|
|
78
|
+
await import_mongoose.default.connect(srvURL);
|
|
79
|
+
console.log("Connected to MongoDB Atlas via +srv URL");
|
|
80
|
+
return true;
|
|
81
|
+
} catch (err) {
|
|
82
|
+
console.warn("+srv connection failed:", err.message);
|
|
83
|
+
console.log("Trying fallback standard connection...");
|
|
84
|
+
try {
|
|
85
|
+
await import_mongoose.default.connect(fallbackURL);
|
|
86
|
+
console.log("Connected to MongoDB Atlas via fallback URL");
|
|
87
|
+
return true;
|
|
88
|
+
} catch (fallbackErr) {
|
|
89
|
+
console.error("Fallback connection failed:", fallbackErr.message);
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
50
95
|
// src/errors/ApiError.ts
|
|
51
96
|
var ApiError = class extends Error {
|
|
52
97
|
constructor(message, statusCode = 500, errors, isOperational = true) {
|
|
@@ -123,8 +168,10 @@ var errorHandler_default = errorHandler;
|
|
|
123
168
|
NotFoundError,
|
|
124
169
|
UnauthorizedError,
|
|
125
170
|
ValidationError,
|
|
171
|
+
connectMongoDb,
|
|
126
172
|
errorMiddleware,
|
|
127
173
|
errorResponse,
|
|
174
|
+
requiredEnv,
|
|
128
175
|
successResponse
|
|
129
176
|
});
|
|
130
177
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +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\";\nexport { errorResponse } from \"./responses/errorResponse\";\
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/responses/successResponse.ts","../src/responses/errorResponse.ts","../src/utils/envManager.ts","../src/config/mongoConfig.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\";\nexport { errorResponse } from \"./responses/errorResponse\";\nexport { requiredEnv } from \"./utils/envManager\";\nexport { connectMongoDb } from \"./config/mongoConfig\";\nexport { default as ApiError } from \"./errors/ApiError\";\nexport { default as BadRequestError } from \"./errors/BadRequestError\";\nexport { default as UnauthorizedError } from \"./errors/UnauthorisedError\";\nexport { default as ForbiddenError } from \"./errors/ForbiddenError\";\nexport { default as NotFoundError } from \"./errors/NotFoundError\";\nexport { default as ValidationError } from \"./errors/ValidationError\";\nexport { default as errorMiddleware } from \"./handlers/errorHandler\";\n\nexport type { SuccessResponse, ErrorResponse } from \"./types/response.types\";\nexport { type MongoConfig } from \"./types/mongoConfig.types\";","import { SuccessResponse } from \"../types/response.types\";\n\nexport const successResponse = <T>(\n data: T,\n message?: string\n): SuccessResponse<T> => ({\n success: true,\n data,\n message,\n});","import { ErrorResponse } from \"../types/response.types\";\n\nexport const errorResponse = (\n message: string,\n errors?: any,\n stack?: string\n): ErrorResponse => ({\n success: false,\n message,\n errors,\n stack,\n});","export const requiredEnv = (value: string | undefined, key: string): string => {\n if (!value) {\n throw new Error(`Missing required environment variable: ${key}`);\n }\n return value;\n};","import mongoose from \"mongoose\";\n\nimport type { MongoConfig } from \"../types/mongoConfig.types\";\n\nexport const connectMongoDb = async (config: MongoConfig) => {\n const { subDomain, userName, password, cluster, dbName } = config;\n // Primary +srv URL\n const srvURL = `mongodb+srv://${userName}:${password}@${cluster.toLowerCase()}.${subDomain}.mongodb.net/${dbName}?retryWrites=true&w=majority&appName=${cluster.toLowerCase()}`;\n // Fallback standard mongodb:// URL (you need to adjust hostnames from Atlas)\n const fallbackURL = `mongodb://${userName}:${password}@ac-hkntio7-shard-00-00.${subDomain}.mongodb.net:27017,ac-hkntio7-shard-00-01.${subDomain}.mongodb.net:27017,ac-hkntio7-shard-00-02.${subDomain}.mongodb.net:27017/${dbName}?ssl=true&replicaSet=atlas-cji6jk-shard-0&authSource=admin&appName=${cluster}`;\n try {\n console.log(\"Trying primary +srv connection...\");\n await mongoose.connect(srvURL);\n console.log(\"Connected to MongoDB Atlas via +srv URL\");\n return true;\n } catch (err: any) {\n console.warn(\"+srv connection failed:\", err.message);\n console.log(\"Trying fallback standard connection...\");\n try {\n await mongoose.connect(fallbackURL);\n console.log(\"Connected to MongoDB Atlas via fallback URL\");\n return true;\n } catch (fallbackErr: any) {\n console.error(\"Fallback connection failed:\", fallbackErr.message);\n return false;\n }\n }\n};","export default class ApiError extends Error {\n statusCode: number;\n isOperational: boolean;\n errors?: any;\n\n constructor(\n message: string,\n statusCode = 500,\n errors?: any,\n isOperational = true\n ) {\n super(message);\n\n this.statusCode = statusCode;\n this.errors = errors;\n this.isOperational = isOperational;\n\n Error.captureStackTrace(this, this.constructor);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class BadRequestError extends ApiError {\n constructor(message = \"Bad Request\", errors?: any) {\n super(message, 400, errors);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class UnauthorizedError extends ApiError {\n constructor(message = \"Unauthorized\", errors?: any) {\n super(message, 401, errors);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class ForbiddenError extends ApiError {\n constructor(message = \"Forbidden\", errors?: any) {\n super(message, 403, errors);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class NotFoundError extends ApiError {\n constructor(message = \"Resource Not Found\", errors?: any) {\n super(message, 404, errors);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class ValidationError extends ApiError {\n constructor(message = \"Validation Failed\", errors?: any) {\n super(message, 422, errors);\n }\n}","// errorHandler.ts\nimport { Request, Response, NextFunction } from \"express\";\nimport ApiError from \"../errors/ApiError\";\nimport { errorResponse } from \"../responses/errorResponse\";\n\nconst routeNotFoundHandler = (req: Request, _: Response, next: NextFunction) => {\n next(new ApiError(`Route ${req.originalUrl} not found`, 404));\n};\n\nconst globalErrorHandler = (err: any, req: Request, res: Response, next: NextFunction) => {\n console.error(\"Error:\", err);\n let statusCode = 500;\n let message = \"Internal Server Error\";\n let errors = undefined;\n let stack = undefined;\n\n if (err instanceof ApiError) {\n statusCode = err.statusCode;\n message = err.message;\n errors = err.errors;\n }\n\n if (process.env.NODE_ENV === \"development\") {\n stack = err.stack;\n }\n\n return res.status(statusCode).json(errorResponse(message, errors, stack));\n};\n\n// Export as a tuple with explicit types so spread works correctly\nconst errorHandler: [\n (req: Request, res: Response, next: NextFunction) => void,\n (err: any, req: Request, res: Response, next: NextFunction) => void\n] = [routeNotFoundHandler, globalErrorHandler];\n\nexport default errorHandler;"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;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;;;ACXO,IAAM,cAAc,CAAC,OAA2B,QAAwB;AAC7E,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,0CAA0C,GAAG,EAAE;AAAA,EACjE;AACA,SAAO;AACT;;;ACLA,sBAAqB;AAId,IAAM,iBAAiB,OAAO,WAAwB;AAC3D,QAAM,EAAE,WAAW,UAAU,UAAU,SAAS,OAAO,IAAI;AAE3D,QAAM,SAAS,iBAAiB,QAAQ,IAAI,QAAQ,IAAI,QAAQ,YAAY,CAAC,IAAI,SAAS,gBAAgB,MAAM,wCAAwC,QAAQ,YAAY,CAAC;AAE7K,QAAM,cAAc,aAAa,QAAQ,IAAI,QAAQ,2BAA2B,SAAS,6CAA6C,SAAS,6CAA6C,SAAS,sBAAsB,MAAM,sEAAsE,OAAO;AAC9S,MAAI;AACF,YAAQ,IAAI,mCAAmC;AAC/C,UAAM,gBAAAA,QAAS,QAAQ,MAAM;AAC7B,YAAQ,IAAI,yCAAyC;AACrD,WAAO;AAAA,EACT,SAAS,KAAU;AACjB,YAAQ,KAAK,2BAA2B,IAAI,OAAO;AACnD,YAAQ,IAAI,wCAAwC;AACpD,QAAI;AACF,YAAM,gBAAAA,QAAS,QAAQ,WAAW;AAClC,cAA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AAEZ,MAAI,eAAe,UAAU;AAC3B,iBAAa,IAAI;AACjB,cAAU,IAAI;AACd,aAAS,IAAI;AAAA,EACf;AAEA,MAAI,QAAQ,IAAI,aAAa,eAAe;AAC1C,YAAQ,IAAI;AAAA,EACd;AAEA,SAAO,IAAI,OAAO,UAAU,EAAE,KAAK,cAAc,SAAS,QAAQ,KAAK,CAAC;AAC1E;AAGA,IAAM,eAGF,CAAC,sBAAsB,kBAAkB;AAE7C,IAAO,uBAAQ;","names":["mongoose"]}
|
package/dist/index.mjs
CHANGED
|
@@ -13,6 +13,39 @@ var errorResponse = (message, errors, stack) => ({
|
|
|
13
13
|
stack
|
|
14
14
|
});
|
|
15
15
|
|
|
16
|
+
// src/utils/envManager.ts
|
|
17
|
+
var requiredEnv = (value, key) => {
|
|
18
|
+
if (!value) {
|
|
19
|
+
throw new Error(`Missing required environment variable: ${key}`);
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// src/config/mongoConfig.ts
|
|
25
|
+
import mongoose from "mongoose";
|
|
26
|
+
var connectMongoDb = async (config) => {
|
|
27
|
+
const { subDomain, userName, password, cluster, dbName } = config;
|
|
28
|
+
const srvURL = `mongodb+srv://${userName}:${password}@${cluster.toLowerCase()}.${subDomain}.mongodb.net/${dbName}?retryWrites=true&w=majority&appName=${cluster.toLowerCase()}`;
|
|
29
|
+
const fallbackURL = `mongodb://${userName}:${password}@ac-hkntio7-shard-00-00.${subDomain}.mongodb.net:27017,ac-hkntio7-shard-00-01.${subDomain}.mongodb.net:27017,ac-hkntio7-shard-00-02.${subDomain}.mongodb.net:27017/${dbName}?ssl=true&replicaSet=atlas-cji6jk-shard-0&authSource=admin&appName=${cluster}`;
|
|
30
|
+
try {
|
|
31
|
+
console.log("Trying primary +srv connection...");
|
|
32
|
+
await mongoose.connect(srvURL);
|
|
33
|
+
console.log("Connected to MongoDB Atlas via +srv URL");
|
|
34
|
+
return true;
|
|
35
|
+
} catch (err) {
|
|
36
|
+
console.warn("+srv connection failed:", err.message);
|
|
37
|
+
console.log("Trying fallback standard connection...");
|
|
38
|
+
try {
|
|
39
|
+
await mongoose.connect(fallbackURL);
|
|
40
|
+
console.log("Connected to MongoDB Atlas via fallback URL");
|
|
41
|
+
return true;
|
|
42
|
+
} catch (fallbackErr) {
|
|
43
|
+
console.error("Fallback connection failed:", fallbackErr.message);
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
|
|
16
49
|
// src/errors/ApiError.ts
|
|
17
50
|
var ApiError = class extends Error {
|
|
18
51
|
constructor(message, statusCode = 500, errors, isOperational = true) {
|
|
@@ -88,8 +121,10 @@ export {
|
|
|
88
121
|
NotFoundError,
|
|
89
122
|
UnauthorizedError,
|
|
90
123
|
ValidationError,
|
|
124
|
+
connectMongoDb,
|
|
91
125
|
errorHandler_default as errorMiddleware,
|
|
92
126
|
errorResponse,
|
|
127
|
+
requiredEnv,
|
|
93
128
|
successResponse
|
|
94
129
|
};
|
|
95
130
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +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\";\n\nexport const successResponse = <T>(\n data: T,\n message?: string\n): SuccessResponse<T> => ({\n success: true,\n data,\n message,\n});","import { ErrorResponse } from \"../types/response.types\";\n\nexport const errorResponse = (\n message: string,\n errors?: any,\n stack?: string\n): ErrorResponse => ({\n success: false,\n message,\n errors,\n stack,\n});","export default class ApiError extends Error {\n statusCode: number;\n isOperational: boolean;\n errors?: any;\n\n constructor(\n message: string,\n statusCode = 500,\n errors?: any,\n isOperational = true\n ) {\n super(message);\n\n this.statusCode = statusCode;\n this.errors = errors;\n this.isOperational = isOperational;\n\n Error.captureStackTrace(this, this.constructor);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class BadRequestError extends ApiError {\n constructor(message = \"Bad Request\", errors?: any) {\n super(message, 400, errors);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class UnauthorizedError extends ApiError {\n constructor(message = \"Unauthorized\", errors?: any) {\n super(message, 401, errors);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class ForbiddenError extends ApiError {\n constructor(message = \"Forbidden\", errors?: any) {\n super(message, 403, errors);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class NotFoundError extends ApiError {\n constructor(message = \"Resource Not Found\", errors?: any) {\n super(message, 404, errors);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class ValidationError extends ApiError {\n constructor(message = \"Validation Failed\", errors?: any) {\n super(message, 422, errors);\n }\n}","// errorHandler.ts\nimport { Request, Response, NextFunction } from \"express\";\nimport ApiError from \"../errors/ApiError\";\nimport { errorResponse } from \"../responses/errorResponse\";\n\nconst routeNotFoundHandler = (req: Request, _: Response, next: NextFunction) => {\n next(new ApiError(`Route ${req.originalUrl} not found`, 404));\n};\n\nconst globalErrorHandler = (err: any, req: Request, res: Response, next: NextFunction) => {\n console.error(\"Error:\", err);\n let statusCode = 500;\n let message = \"Internal Server Error\";\n let errors = undefined;\n let stack = undefined;\n\n if (err instanceof ApiError) {\n statusCode = err.statusCode;\n message = err.message;\n errors = err.errors;\n }\n\n if (process.env.NODE_ENV === \"development\") {\n stack = err.stack;\n }\n\n return res.status(statusCode).json(errorResponse(message, errors, stack));\n};\n\n// Export as a tuple with explicit types so spread works correctly\nconst errorHandler: [\n (req: Request, res: Response, next: NextFunction) => void,\n (err: any, req: Request, res: Response, next: NextFunction) => void\n] = [routeNotFoundHandler, globalErrorHandler];\n\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;;;
|
|
1
|
+
{"version":3,"sources":["../src/responses/successResponse.ts","../src/responses/errorResponse.ts","../src/utils/envManager.ts","../src/config/mongoConfig.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\";\n\nexport const successResponse = <T>(\n data: T,\n message?: string\n): SuccessResponse<T> => ({\n success: true,\n data,\n message,\n});","import { ErrorResponse } from \"../types/response.types\";\n\nexport const errorResponse = (\n message: string,\n errors?: any,\n stack?: string\n): ErrorResponse => ({\n success: false,\n message,\n errors,\n stack,\n});","export const requiredEnv = (value: string | undefined, key: string): string => {\n if (!value) {\n throw new Error(`Missing required environment variable: ${key}`);\n }\n return value;\n};","import mongoose from \"mongoose\";\n\nimport type { MongoConfig } from \"../types/mongoConfig.types\";\n\nexport const connectMongoDb = async (config: MongoConfig) => {\n const { subDomain, userName, password, cluster, dbName } = config;\n // Primary +srv URL\n const srvURL = `mongodb+srv://${userName}:${password}@${cluster.toLowerCase()}.${subDomain}.mongodb.net/${dbName}?retryWrites=true&w=majority&appName=${cluster.toLowerCase()}`;\n // Fallback standard mongodb:// URL (you need to adjust hostnames from Atlas)\n const fallbackURL = `mongodb://${userName}:${password}@ac-hkntio7-shard-00-00.${subDomain}.mongodb.net:27017,ac-hkntio7-shard-00-01.${subDomain}.mongodb.net:27017,ac-hkntio7-shard-00-02.${subDomain}.mongodb.net:27017/${dbName}?ssl=true&replicaSet=atlas-cji6jk-shard-0&authSource=admin&appName=${cluster}`;\n try {\n console.log(\"Trying primary +srv connection...\");\n await mongoose.connect(srvURL);\n console.log(\"Connected to MongoDB Atlas via +srv URL\");\n return true;\n } catch (err: any) {\n console.warn(\"+srv connection failed:\", err.message);\n console.log(\"Trying fallback standard connection...\");\n try {\n await mongoose.connect(fallbackURL);\n console.log(\"Connected to MongoDB Atlas via fallback URL\");\n return true;\n } catch (fallbackErr: any) {\n console.error(\"Fallback connection failed:\", fallbackErr.message);\n return false;\n }\n }\n};","export default class ApiError extends Error {\n statusCode: number;\n isOperational: boolean;\n errors?: any;\n\n constructor(\n message: string,\n statusCode = 500,\n errors?: any,\n isOperational = true\n ) {\n super(message);\n\n this.statusCode = statusCode;\n this.errors = errors;\n this.isOperational = isOperational;\n\n Error.captureStackTrace(this, this.constructor);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class BadRequestError extends ApiError {\n constructor(message = \"Bad Request\", errors?: any) {\n super(message, 400, errors);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class UnauthorizedError extends ApiError {\n constructor(message = \"Unauthorized\", errors?: any) {\n super(message, 401, errors);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class ForbiddenError extends ApiError {\n constructor(message = \"Forbidden\", errors?: any) {\n super(message, 403, errors);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class NotFoundError extends ApiError {\n constructor(message = \"Resource Not Found\", errors?: any) {\n super(message, 404, errors);\n }\n}","import ApiError from \"./ApiError\";\n\nexport default class ValidationError extends ApiError {\n constructor(message = \"Validation Failed\", errors?: any) {\n super(message, 422, errors);\n }\n}","// errorHandler.ts\nimport { Request, Response, NextFunction } from \"express\";\nimport ApiError from \"../errors/ApiError\";\nimport { errorResponse } from \"../responses/errorResponse\";\n\nconst routeNotFoundHandler = (req: Request, _: Response, next: NextFunction) => {\n next(new ApiError(`Route ${req.originalUrl} not found`, 404));\n};\n\nconst globalErrorHandler = (err: any, req: Request, res: Response, next: NextFunction) => {\n console.error(\"Error:\", err);\n let statusCode = 500;\n let message = \"Internal Server Error\";\n let errors = undefined;\n let stack = undefined;\n\n if (err instanceof ApiError) {\n statusCode = err.statusCode;\n message = err.message;\n errors = err.errors;\n }\n\n if (process.env.NODE_ENV === \"development\") {\n stack = err.stack;\n }\n\n return res.status(statusCode).json(errorResponse(message, errors, stack));\n};\n\n// Export as a tuple with explicit types so spread works correctly\nconst errorHandler: [\n (req: Request, res: Response, next: NextFunction) => void,\n (err: any, req: Request, res: Response, next: NextFunction) => void\n] = [routeNotFoundHandler, globalErrorHandler];\n\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;;;ACXO,IAAM,cAAc,CAAC,OAA2B,QAAwB;AAC7E,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,0CAA0C,GAAG,EAAE;AAAA,EACjE;AACA,SAAO;AACT;;;ACLA,OAAO,cAAc;AAId,IAAM,iBAAiB,OAAO,WAAwB;AAC3D,QAAM,EAAE,WAAW,UAAU,UAAU,SAAS,OAAO,IAAI;AAE3D,QAAM,SAAS,iBAAiB,QAAQ,IAAI,QAAQ,IAAI,QAAQ,YAAY,CAAC,IAAI,SAAS,gBAAgB,MAAM,wCAAwC,QAAQ,YAAY,CAAC;AAE7K,QAAM,cAAc,aAAa,QAAQ,IAAI,QAAQ,2BAA2B,SAAS,6CAA6C,SAAS,6CAA6C,SAAS,sBAAsB,MAAM,sEAAsE,OAAO;AAC9S,MAAI;AACF,YAAQ,IAAI,mCAAmC;AAC/C,UAAM,SAAS,QAAQ,MAAM;AAC7B,YAAQ,IAAI,yCAAyC;AACrD,WAAO;AAAA,EACT,SAAS,KAAU;AACjB,YAAQ,KAAK,2BAA2B,IAAI,OAAO;AACnD,YAAQ,IAAI,wCAAwC;AACpD,QAAI;AACF,YAAM,SAAS,QAAQ,WAAW;AAClC,cAAQ,IAAI,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AI,eAAe,UAAU;AAC3B,iBAAa,IAAI;AACjB,cAAU,IAAI;AACd,aAAS,IAAI;AAAA,EACf;AAEA,MAAI,QAAQ,IAAI,aAAa,eAAe;AAC1C,YAAQ,IAAI;AAAA,EACd;AAEA,SAAO,IAAI,OAAO,UAAU,EAAE,KAAK,cAAc,SAAS,QAAQ,KAAK,CAAC;AAC1E;AAGA,IAAM,eAGF,CAAC,sBAAsB,kBAAkB;AAE7C,IAAO,uBAAQ;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nexus-backend",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
4
|
"description": "Backend utility library for Express.js",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -12,11 +12,20 @@
|
|
|
12
12
|
"build": "tsup"
|
|
13
13
|
},
|
|
14
14
|
"peerDependencies": {
|
|
15
|
-
"
|
|
15
|
+
"cookie-parser": "^1.4.7",
|
|
16
|
+
"cors": "^2.8.6",
|
|
17
|
+
"dotenv": "^17.4.2",
|
|
18
|
+
"express": "^5.0.6",
|
|
19
|
+
"helmet": "^8.1.0",
|
|
20
|
+
"mongoose": "^9.6.2",
|
|
21
|
+
"morgan": "^1.10.1",
|
|
22
|
+
"socket.io": "^4.8.3"
|
|
16
23
|
},
|
|
17
24
|
"devDependencies": {
|
|
25
|
+
"@types/cookie-parser": "^1.4.10",
|
|
26
|
+
"@types/cors": "^2.8.19",
|
|
18
27
|
"@types/express": "^5.0.6",
|
|
19
28
|
"tsup": "^8.5.1",
|
|
20
29
|
"typescript": "^5.8.3"
|
|
21
30
|
}
|
|
22
|
-
}
|
|
31
|
+
}
|