@codenokami/node-api-master 1.4.0 β†’ 1.4.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 CHANGED
@@ -1,164 +1,99 @@
1
- ο»Ώ# @cnk/node-api-master πŸš€
1
+ ο»Ώ# @codenokami/node-api-master πŸš€
2
2
 
3
- A robust, professional-grade utility package for Express.js APIs. This package simplifies database connections, authentication, real-time communication with Socket.io, error handling, and request validation.
3
+ A modern, robust, and professional Node.js utility package for building scalable REST APIs. Built with **ES Modules** and **TypeScript Support**, providing dual-format (CJS & ESM) compatibility.
4
4
 
5
5
  ---
6
6
 
7
- ## πŸ“¦ Installation
8
-
9
- This package is designed to work with **mongoose** and **socket.io** as peer dependencies to avoid version conflicts.
10
-
11
- ```bash
12
- # Install the core package
13
- npm install @cnk/node-api-master
14
-
15
- # Install required peer dependencies
16
- npm install mongoose socket.io
17
-
18
- ```
19
-
20
- ---
7
+ ## ✨ Features
21
8
 
22
- ## πŸ“‚ Features
23
-
24
- - **πŸ›‘ Auth & Admin Middleware**: JWT-based route protection and role-based access control.
25
- - **πŸ”Œ Socket.io Helper**: Integrated real-time communication with JWT authentication support.
26
- - **🚨 Global Error Handler**: Centralized error management using the `AppError` class.
27
- - **⚑ CatchAsync Utility**: Eliminate repetitive `try-catch` blocks in your controllers.
28
- - **βœ… Joi Validation**: Pre-defined and custom schemas for request validation.
29
- - **πŸ”— DB Helper**: Simplified MongoDB connection setup.
30
- - **πŸ“Š Standardized Responses**: Uniform success and error API response formats.
9
+ - πŸ›  **Standard API Response**: Consistent success and error response wrappers.
10
+ - πŸ›‘ **Global Error Handling**: Centralized error middleware with operational vs programming error detection.
11
+ - ⚑ **Async Handler**: Eliminate the need for messy `try-catch` blocks in controllers.
12
+ - πŸ§ͺ **Joi Validations**: Pre-defined schemas for users, object IDs, and pagination.
13
+ - πŸ”‘ **Auth Helpers**: Robust password hashing and JWT management.
14
+ - πŸ†” **Secure UUID**: RFC 4122 compliant UUID v4 generator.
15
+ - πŸ”Œ **Socket.io Auth**: Middleware for securing your real-time connections.
31
16
 
32
17
  ---
33
18
 
34
- ## πŸ“– Detailed Usage Guide
35
-
36
- ### 1. Database Connection & Server Setup
37
-
38
- Handle dynamic ports and database connections efficiently.
39
-
40
- ```javascript
41
- const { connectDB, STATUS_CODES } = require("@cnk/node-api-master");
42
-
43
- // Start DB
44
- connectDB(process.env.MONGO_URI);
19
+ ## πŸ“¦ Installation
45
20
 
46
- // Dynamic Port
47
- const PORT = process.env.PORT || 5000;
48
- app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
21
+ ```bash
22
+ npm install @codenokami/node-api-master
49
23
  ```
50
24
 
51
25
  ---
52
26
 
53
- ### 2. Socket.io with Authentication
54
-
55
- Setup a secure real-time server. The middleware automatically verifies tokens from `socket.handshake.auth.token`.
56
-
57
- ```javascript
58
- const http = require("http");
59
- const { socket } = require("@cnk/node-api-master");
60
-
61
- const server = http.createServer(app);
62
-
63
- // Initialize Socket with JWT protection
64
- const io = socket.initSocket(server, {
65
- authRequired: true,
66
- jwtSecret: process.env.JWT_SECRET,
67
- });
68
-
69
- io.on("connection", (s) => {
70
- console.log("Authenticated User ID:", s.user.id);
71
- });
72
-
73
- server.listen(PORT);
74
- ```
27
+ ## πŸš€ Quick Start
75
28
 
76
- ---
77
-
78
- ### 3. Authentication Middleware (HTTP)
29
+ ### 1. Setup Global Error Middleware
79
30
 
80
- Protect your Express routes using JWT.
31
+ In your main app file (e.g., `index.js` or `app.js`):
81
32
 
82
33
  ```javascript
83
- const { auth, admin } = require("@cnk/node-api-master");
84
-
85
- // Protect a route
86
- router.get("/me", auth(), userController.getMe);
87
-
88
- // Admin only route
89
- router.delete("/users/:id", auth(), admin, userController.deleteUser);
90
- ```
91
-
92
- ---
93
-
94
- ### 4. Request Validation (Joi)
95
-
96
- Validate incoming request bodies, params, or queries.
34
+ import express from "express";
35
+ import { errorMiddleware } from "@codenokami/node-api-master";
97
36
 
98
- ```javascript
99
- const { validate, schemas, Joi } = require("@cnk/node-api-master");
37
+ const app = express();
100
38
 
101
- // Use pre-built schemas
102
- router.post("/login", validate(schemas.user.login), authController.login);
39
+ // ... your routes ...
103
40
 
104
- // Use custom schema
105
- const profileSchema = Joi.object({
106
- bio: Joi.string().max(200),
107
- website: Joi.string().uri(),
108
- });
109
- router.put("/profile", validate(profileSchema), userController.updateProfile);
41
+ // Must be at the end of all routes
42
+ app.use(errorMiddleware);
110
43
  ```
111
44
 
112
- ---
113
-
114
- ### 5. Standardized Responses & Error Handling
45
+ ### 2. Using catchAsync & apiResponse
115
46
 
116
- Keep your API responses consistent across the entire project.
47
+ Clean up your controllers easily:
117
48
 
118
49
  ```javascript
119
- const {
120
- catchAsync,
121
- AppError,
122
- apiResponse,
123
- STATUS_CODES,
124
- } = require("@cnk/node-api-master");
125
-
126
- exports.getUser = catchAsync(async (req, res, next) => {
50
+ import { catchAsync, apiResponse, AppError } from "@codenokami/node-api-master";
51
+
52
+ export const getUser = catchAsync(async (req, res, next) => {
127
53
  const user = await User.findById(req.params.id);
128
54
 
129
55
  if (!user) {
130
- return next(new AppError("User not found!", STATUS_CODES.NOT_FOUND));
56
+ return next(new AppError("User not found", 404));
131
57
  }
132
58
 
133
- apiResponse.success(res, user, "User retrieved successfully");
59
+ return apiResponse.success(res, user, "User retrieved successfully");
134
60
  });
135
61
  ```
136
62
 
137
- ---
138
-
139
- ### 6. Global Error Middleware
63
+ ### 3. Validating Requests
140
64
 
141
- **Mandatory:** Register this at the very end of your middleware stack in `app.js`.
65
+ Use pre-built Joi schemas:
142
66
 
143
67
  ```javascript
144
- const { errorMiddleware } = require("@cnk/node-api-master");
145
-
146
- // After all your routes
147
- app.use(errorMiddleware);
68
+ import { validate, schemas } from "@codenokami/node-api-master";
69
+
70
+ // Apply validation as middleware
71
+ router.post(
72
+ "/register",
73
+ validate(schemas.user.register),
74
+ authController.register,
75
+ );
148
76
  ```
149
77
 
150
78
  ---
151
79
 
152
- ## πŸ›  Project Structure
80
+ ## πŸ›  Utilities Reference
153
81
 
154
- - `src/db`: Mongoose connection helpers.
155
- - `src/middleware`: Auth, Admin, Validation, and Global Error handlers.
156
- - `src/socket`: Socket.io initialization and JWT middleware.
157
- - `src/utils`: `AppError`, `catchAsync`, and API response helpers.
158
- - `src/validations`: Reusable Joi schemas.
82
+ | Utility | Description |
83
+ | -------------------------------------- | ---------------------------------------------------------- |
84
+ | `generateUUID()` | Returns a secure v4 UUID string. |
85
+ | `authHelper.hashPassword(pw)` | Hashes password using bcrypt. |
86
+ | `authHelper.comparePassword(pw, hash)` | Compares plain text password with hash. |
87
+ | `STATUS_CODES` | Standard HTTP Status codes (OK: 200, NOT_FOUND: 404, etc.) |
159
88
 
160
89
  ---
161
90
 
162
- ## πŸ“„ License
91
+ ## πŸ— Build Status
92
+
93
+ - **ES Modules (ESM)**: Supported (`.mjs`)
94
+ - **CommonJS (CJS)**: Supported (`.cjs`)
95
+ - **TypeScript**: Type definitions included (`.d.ts`)
96
+
97
+ ## πŸ“œ License
163
98
 
164
- MIT Β© CNK
99
+ MIT Β© CodeNoKami
package/dist/index.d.mts CHANGED
@@ -240,10 +240,6 @@ const apiResponse = {
240
240
  },
241
241
  };
242
242
 
243
- declare namespace response {
244
- export { apiResponse as default };
245
- }
246
-
247
243
  /**
248
244
  * Password α€€α€­α€― Hash α€œα€―α€•α€Ία€›α€”α€Ί
249
245
  */
@@ -433,4 +429,4 @@ declare namespace index {
433
429
  export { index_getIO as getIO, index_initSocket as initSocket };
434
430
  }
435
431
 
436
- export { AppError, STATUS_CODES, admin, response as apiResponse, auth, catchAsync, comparePassword, connectDB, errorMiddleware, generateToken, generateUUID, hashPassword, schemas, index as socket, validate };
432
+ export { AppError, STATUS_CODES, admin, apiResponse, auth, catchAsync, comparePassword, connectDB, errorMiddleware, generateToken, generateUUID, hashPassword, schemas, index as socket, validate };
package/dist/index.d.ts CHANGED
@@ -240,10 +240,6 @@ const apiResponse = {
240
240
  },
241
241
  };
242
242
 
243
- declare namespace response {
244
- export { apiResponse as default };
245
- }
246
-
247
243
  /**
248
244
  * Password α€€α€­α€― Hash α€œα€―α€•α€Ία€›α€”α€Ί
249
245
  */
@@ -433,4 +429,4 @@ declare namespace index {
433
429
  export { index_getIO as getIO, index_initSocket as initSocket };
434
430
  }
435
431
 
436
- export { AppError, STATUS_CODES, admin, response as apiResponse, auth, catchAsync, comparePassword, connectDB, errorMiddleware, generateToken, generateUUID, hashPassword, schemas, index as socket, validate };
432
+ export { AppError, STATUS_CODES, admin, apiResponse, auth, catchAsync, comparePassword, connectDB, errorMiddleware, generateToken, generateUUID, hashPassword, schemas, index as socket, validate };
package/dist/index.js CHANGED
@@ -33,7 +33,7 @@ __export(index_exports, {
33
33
  Joi: () => import_joi3.default,
34
34
  STATUS_CODES: () => constants_default,
35
35
  admin: () => admin,
36
- apiResponse: () => response_exports,
36
+ apiResponse: () => response_default,
37
37
  auth: () => auth,
38
38
  catchAsync: () => catchAsync_default,
39
39
  comparePassword: () => comparePassword,
@@ -224,10 +224,6 @@ var errorMiddleware = (err, req, res, next) => {
224
224
  var errorMiddleware_default = errorMiddleware;
225
225
 
226
226
  // src/utils/response.js
227
- var response_exports = {};
228
- __export(response_exports, {
229
- default: () => response_default
230
- });
231
227
  var apiResponse = {
232
228
  // ထောင်မြင်တဲ့ response ပေးပို့ရန်
233
229
  success: (res, data, message = "Success", statusCode = constants_default.OK) => {
package/dist/index.mjs CHANGED
@@ -182,10 +182,6 @@ var errorMiddleware = (err, req, res, next) => {
182
182
  var errorMiddleware_default = errorMiddleware;
183
183
 
184
184
  // src/utils/response.js
185
- var response_exports = {};
186
- __export(response_exports, {
187
- default: () => response_default
188
- });
189
185
  var apiResponse = {
190
186
  // ထောင်မြင်တဲ့ response ပေးပို့ရန်
191
187
  success: (res, data, message = "Success", statusCode = constants_default.OK) => {
@@ -357,7 +353,7 @@ export {
357
353
  Joi3 as Joi,
358
354
  constants_default as STATUS_CODES,
359
355
  admin,
360
- response_exports as apiResponse,
356
+ response_default as apiResponse,
361
357
  auth,
362
358
  catchAsync_default as catchAsync,
363
359
  comparePassword,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codenokami/node-api-master",
3
- "version": "1.4.0",
3
+ "version": "1.4.2",
4
4
  "description": "Professional utility package for Express.js APIs with Auth, Socket, and Error Handling",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.mjs",