@codenokami/node-api-master 1.4.1 → 1.5.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,20 @@
1
+ /**
2
+ * Custom Error Class for API Errors
3
+ */
4
+ class AppError extends Error {
5
+ constructor(message, statusCode) {
6
+ super(message);
7
+
8
+ this.statusCode = statusCode;
9
+ // status က 4xx ဆိုရင် 'fail', 5xx ဆိုရင် 'error' လို့ သတ်မှတ်မယ်
10
+ this.status = `${statusCode}`.startsWith("4") ? "fail" : "error";
11
+
12
+ // ဒါက ကျွန်တော်တို့ကိုယ်တိုင် သတ်မှတ်လိုက်တဲ့ Error ဖြစ်ကြောင်း အမှတ်အသားပြုတာပါ
13
+ this.isOperational = true;
14
+
15
+ // Error ဘယ်နေရာမှာ ဖြစ်တယ်ဆိုတဲ့ stack trace ကို သိမ်းထားမယ်
16
+ Error.captureStackTrace(this, this.constructor);
17
+ }
18
+ }
19
+
20
+ export { AppError as A };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Custom Error Class for API Errors
3
+ */
4
+ class AppError extends Error {
5
+ constructor(message, statusCode) {
6
+ super(message);
7
+
8
+ this.statusCode = statusCode;
9
+ // status က 4xx ဆိုရင် 'fail', 5xx ဆိုရင် 'error' လို့ သတ်မှတ်မယ်
10
+ this.status = `${statusCode}`.startsWith("4") ? "fail" : "error";
11
+
12
+ // ဒါက ကျွန်တော်တို့ကိုယ်တိုင် သတ်မှတ်လိုက်တဲ့ Error ဖြစ်ကြောင်း အမှတ်အသားပြုတာပါ
13
+ this.isOperational = true;
14
+
15
+ // Error ဘယ်နေရာမှာ ဖြစ်တယ်ဆိုတဲ့ stack trace ကို သိမ်းထားမယ်
16
+ Error.captureStackTrace(this, this.constructor);
17
+ }
18
+ }
19
+
20
+ export { AppError as A };
@@ -0,0 +1 @@
1
+ var t=class extends Error{constructor(s,r){super(s),this.statusCode=r,this.status=`${r}`.startsWith("4")?"fail":"error",this.isOperational=!0,Error.captureStackTrace(this,this.constructor)}},e=t;export{e as a};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var t=class extends Error{constructor(s,r){super(s),this.statusCode=r,this.status=`${r}`.startsWith("4")?"fail":"error",this.isOperational=!0,Error.captureStackTrace(this,this.constructor)}},e= exports.a =t;exports.a = e;
package/dist/index.d.mts CHANGED
@@ -1,10 +1,8 @@
1
- import Joi from 'joi';
2
- export { default as Joi } from 'joi';
3
1
  import mongoose from 'mongoose';
4
2
  import jwt from 'jsonwebtoken';
3
+ import { A as AppError } from './AppError-ByGDb4IL.mjs';
5
4
  import bcrypt from 'bcryptjs';
6
5
  import crypto from 'crypto';
7
- import { Server } from 'socket.io';
8
6
 
9
7
  /**
10
8
  * Database သို့ ချိတ်ဆက်ပေးသော function
@@ -27,25 +25,6 @@ const connectDB = async (url) => {
27
25
  }
28
26
  };
29
27
 
30
- /**
31
- * Custom Error Class for API Errors
32
- */
33
- class AppError extends Error {
34
- constructor(message, statusCode) {
35
- super(message);
36
-
37
- this.statusCode = statusCode;
38
- // status က 4xx ဆိုရင် 'fail', 5xx ဆိုရင် 'error' လို့ သတ်မှတ်မယ်
39
- this.status = `${statusCode}`.startsWith("4") ? "fail" : "error";
40
-
41
- // ဒါက ကျွန်တော်တို့ကိုယ်တိုင် သတ်မှတ်လိုက်တဲ့ Error ဖြစ်ကြောင်း အမှတ်အသားပြုတာပါ
42
- this.isOperational = true;
43
-
44
- // Error ဘယ်နေရာမှာ ဖြစ်တယ်ဆိုတဲ့ stack trace ကို သိမ်းထားမယ်
45
- Error.captureStackTrace(this, this.constructor);
46
- }
47
- }
48
-
49
28
  /**
50
29
  * catchAsync - try-catch block တွေကို အစားထိုးရန်
51
30
  * @param {Function} fn - Async controller function
@@ -61,7 +40,7 @@ const catchAsync = (fn) => {
61
40
  * Auth Middleware - Supports Bearer Token & Cookies
62
41
  * @param {string} secret - JWT Secret (Default is process.env.JWT_SECRET)
63
42
  */
64
- const auth = (secret = process.env.JWT_SECRET) =>
43
+ const auth = (secret = process.env.JWT_SECRET, options = {}) =>
65
44
  catchAsync(async (req, res, next) => {
66
45
  let token;
67
46
 
@@ -73,8 +52,8 @@ const auth = (secret = process.env.JWT_SECRET) =>
73
52
  token = req.headers.authorization.split(" ")[1];
74
53
  }
75
54
  // 2) Cookie ကနေ Token ကို စစ်ဆေးခြင်း
76
- else if (req.cookies && req.cookies.jwt) {
77
- token = req.cookies.jwt;
55
+ else if (req.cookies && req.cookies[options.cookieName || "jwt"]) {
56
+ token = req.cookies[options.cookieName || "jwt"];
78
57
  }
79
58
 
80
59
  // Secret မရှိရင် Developer ကို သတိပေးဖို့ Error ပြမယ်
@@ -118,32 +97,6 @@ const admin = (req, res, next) => {
118
97
  }
119
98
  };
120
99
 
121
- /**
122
- * Joi Schema Validation Middleware
123
- * @param {Object} schema - Joi validation schema
124
- */
125
- const validate = (schema) => (req, res, next) => {
126
- // body, query, params အားလုံးကို စစ်လို့ရအောင် req object တစ်ခုလုံးကို schema နဲ့ တိုက်စစ်မယ်
127
- const { error, value } = schema.validate(req.body, {
128
- abortEarly: false, // Error အားလုံးကို တစ်ခါတည်း ပြရန်
129
- allowUnknown: true, // Schema ထဲမပါတဲ့ field တွေပါလာရင် လက်ခံရန်
130
- stripUnknown: true, // Schema ထဲမပါတဲ့ field တွေကို ဖယ်ထုတ်ပစ်ရန်
131
- });
132
-
133
- if (error) {
134
- // Error message တွေကို စုစည်းပြီး format လုပ်မယ်
135
- const errorMessage = error.details
136
- .map((detail) => detail.message.replace(/"/g, ""))
137
- .join(", ");
138
-
139
- return next(new AppError(errorMessage, 400));
140
- }
141
-
142
- // စစ်ဆေးပြီးသား data (sanitized data) ကို req.body ထဲ ပြန်ထည့်မယ်
143
- req.body = value;
144
- next();
145
- };
146
-
147
100
  /**
148
101
  * Standard HTTP Status Codes
149
102
  */
@@ -240,10 +193,6 @@ const apiResponse = {
240
193
  },
241
194
  };
242
195
 
243
- declare namespace response {
244
- export { apiResponse as default };
245
- }
246
-
247
196
  /**
248
197
  * Password ကို Hash လုပ်ရန်
249
198
  */
@@ -306,131 +255,4 @@ const generateUUID = () => {
306
255
  );
307
256
  };
308
257
 
309
- /**
310
- * User Validation Schemas
311
- */
312
- const userSchema = {
313
- // Standard Register Schema
314
- register: Joi.object({
315
- username: Joi.string().alphanum().min(3).max(30).required().messages({
316
- "string.min": "Username must be at least 3 characters long",
317
- "any.required": "Username is a required field",
318
- }),
319
- email: Joi.string()
320
- .email({ minDomainSegments: 2, tlds: { allow: ["com", "net", "org"] } })
321
- .required()
322
- .messages({
323
- "string.email": "Please provide a valid email address",
324
- }),
325
- password: Joi.string().min(8).required().messages({
326
- "string.min": "Password must be at least 8 characters long",
327
- }),
328
- confirmPassword: Joi.any()
329
- .equal(Joi.ref("password"))
330
- .required()
331
- .messages({ "any.only": "Passwords do not match" }),
332
- role: Joi.string().valid("user", "admin").default("user"),
333
- }),
334
-
335
- // Login Schema
336
- login: Joi.object({
337
- email: Joi.string().email().required(),
338
- password: Joi.string().required(),
339
- }),
340
-
341
- // Password Update Schema
342
- updatePassword: Joi.object({
343
- currentPassword: Joi.string().required(),
344
- newPassword: Joi.string().min(8).required(),
345
- }),
346
-
347
- /**
348
- * စိတ်ကြိုက် schema အသစ်ဆောက်ချင်ရင် သုံးရန် (Dynamic Flexibility)
349
- * @param {Object} schemaDefinition - Joi object definition
350
- */
351
- custom: (schemaDefinition) => Joi.object(schemaDefinition),
352
- };
353
-
354
- /**
355
- * Common Joi Schemas
356
- */
357
- const commonSchema = {
358
- // MongoDB ObjectId စစ်ဆေးရန် (24 hex characters)
359
- objectId: Joi.string()
360
- .regex(/^[0-9a-fA-F]{24}$/)
361
- .messages({
362
- "string.pattern.base": "Invalid ID format. Must be a valid ObjectId.",
363
- }),
364
-
365
- // Pagination အတွက် (Query strings)
366
- pagination: Joi.object({
367
- page: Joi.number().integer().min(1).default(1),
368
- limit: Joi.number().integer().min(1).max(100).default(10),
369
- sort: Joi.string().optional(),
370
- fields: Joi.string().optional(),
371
- }),
372
- };
373
-
374
- const schemas = {
375
- user: userSchema,
376
- common: commonSchema,
377
- };
378
-
379
- let io;
380
-
381
- /**
382
- * Socket Authentication Middleware
383
- */
384
- const socketAuth = (secret) => {
385
- return (socket, next) => {
386
- const token =
387
- socket.handshake.auth?.token || socket.handshake.headers?.token;
388
-
389
- if (!token) {
390
- return next(new Error("Authentication error: Token missing"));
391
- }
392
-
393
- try {
394
- const decoded = jwt.verify(token, secret || process.env.JWT_SECRET);
395
- socket.user = decoded; // socket ထဲမှာ user data သိမ်းထားမယ်
396
- next();
397
- } catch (err) {
398
- next(new Error("Authentication error: Invalid token"));
399
- }
400
- };
401
- };
402
-
403
- /**
404
- * Socket Initialize လုပ်ခြင်း
405
- */
406
- const initSocket = (server, options = {}) => {
407
- io = new Server(server, {
408
- cors: {
409
- origin: options.origin || "*",
410
- },
411
- ...options,
412
- });
413
-
414
- // JWT Middleware ကို အသုံးပြုခြင်း
415
- if (options.authRequired) {
416
- io.use(socketAuth(options.jwtSecret));
417
- }
418
-
419
- return io;
420
- };
421
-
422
- /**
423
- * Initialize ပြီးသား IO object ကို ပြန်ယူခြင်း
424
- */
425
- const getIO = () => {
426
- if (!io) throw new Error("Socket.io not initialized!");
427
- return io;
428
- };
429
-
430
- declare const index_getIO: typeof getIO;
431
- declare const index_initSocket: typeof initSocket;
432
- declare namespace index {
433
- export { index_getIO as getIO, index_initSocket as initSocket };
434
- }
435
-
436
- export { AppError, STATUS_CODES, admin, response as apiResponse, auth, catchAsync, comparePassword, connectDB, errorMiddleware, generateToken, generateUUID, hashPassword, schemas, index as socket, validate };
258
+ export { AppError, STATUS_CODES, admin, apiResponse, auth, catchAsync, comparePassword, connectDB, errorMiddleware, generateToken, generateUUID, hashPassword };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,8 @@
1
- import Joi from 'joi';
2
- export { default as Joi } from 'joi';
3
1
  import mongoose from 'mongoose';
4
2
  import jwt from 'jsonwebtoken';
3
+ import { A as AppError } from './AppError-ByGDb4IL.js';
5
4
  import bcrypt from 'bcryptjs';
6
5
  import crypto from 'crypto';
7
- import { Server } from 'socket.io';
8
6
 
9
7
  /**
10
8
  * Database သို့ ချိတ်ဆက်ပေးသော function
@@ -27,25 +25,6 @@ const connectDB = async (url) => {
27
25
  }
28
26
  };
29
27
 
30
- /**
31
- * Custom Error Class for API Errors
32
- */
33
- class AppError extends Error {
34
- constructor(message, statusCode) {
35
- super(message);
36
-
37
- this.statusCode = statusCode;
38
- // status က 4xx ဆိုရင် 'fail', 5xx ဆိုရင် 'error' လို့ သတ်မှတ်မယ်
39
- this.status = `${statusCode}`.startsWith("4") ? "fail" : "error";
40
-
41
- // ဒါက ကျွန်တော်တို့ကိုယ်တိုင် သတ်မှတ်လိုက်တဲ့ Error ဖြစ်ကြောင်း အမှတ်အသားပြုတာပါ
42
- this.isOperational = true;
43
-
44
- // Error ဘယ်နေရာမှာ ဖြစ်တယ်ဆိုတဲ့ stack trace ကို သိမ်းထားမယ်
45
- Error.captureStackTrace(this, this.constructor);
46
- }
47
- }
48
-
49
28
  /**
50
29
  * catchAsync - try-catch block တွေကို အစားထိုးရန်
51
30
  * @param {Function} fn - Async controller function
@@ -61,7 +40,7 @@ const catchAsync = (fn) => {
61
40
  * Auth Middleware - Supports Bearer Token & Cookies
62
41
  * @param {string} secret - JWT Secret (Default is process.env.JWT_SECRET)
63
42
  */
64
- const auth = (secret = process.env.JWT_SECRET) =>
43
+ const auth = (secret = process.env.JWT_SECRET, options = {}) =>
65
44
  catchAsync(async (req, res, next) => {
66
45
  let token;
67
46
 
@@ -73,8 +52,8 @@ const auth = (secret = process.env.JWT_SECRET) =>
73
52
  token = req.headers.authorization.split(" ")[1];
74
53
  }
75
54
  // 2) Cookie ကနေ Token ကို စစ်ဆေးခြင်း
76
- else if (req.cookies && req.cookies.jwt) {
77
- token = req.cookies.jwt;
55
+ else if (req.cookies && req.cookies[options.cookieName || "jwt"]) {
56
+ token = req.cookies[options.cookieName || "jwt"];
78
57
  }
79
58
 
80
59
  // Secret မရှိရင် Developer ကို သတိပေးဖို့ Error ပြမယ်
@@ -118,32 +97,6 @@ const admin = (req, res, next) => {
118
97
  }
119
98
  };
120
99
 
121
- /**
122
- * Joi Schema Validation Middleware
123
- * @param {Object} schema - Joi validation schema
124
- */
125
- const validate = (schema) => (req, res, next) => {
126
- // body, query, params အားလုံးကို စစ်လို့ရအောင် req object တစ်ခုလုံးကို schema နဲ့ တိုက်စစ်မယ်
127
- const { error, value } = schema.validate(req.body, {
128
- abortEarly: false, // Error အားလုံးကို တစ်ခါတည်း ပြရန်
129
- allowUnknown: true, // Schema ထဲမပါတဲ့ field တွေပါလာရင် လက်ခံရန်
130
- stripUnknown: true, // Schema ထဲမပါတဲ့ field တွေကို ဖယ်ထုတ်ပစ်ရန်
131
- });
132
-
133
- if (error) {
134
- // Error message တွေကို စုစည်းပြီး format လုပ်မယ်
135
- const errorMessage = error.details
136
- .map((detail) => detail.message.replace(/"/g, ""))
137
- .join(", ");
138
-
139
- return next(new AppError(errorMessage, 400));
140
- }
141
-
142
- // စစ်ဆေးပြီးသား data (sanitized data) ကို req.body ထဲ ပြန်ထည့်မယ်
143
- req.body = value;
144
- next();
145
- };
146
-
147
100
  /**
148
101
  * Standard HTTP Status Codes
149
102
  */
@@ -240,10 +193,6 @@ const apiResponse = {
240
193
  },
241
194
  };
242
195
 
243
- declare namespace response {
244
- export { apiResponse as default };
245
- }
246
-
247
196
  /**
248
197
  * Password ကို Hash လုပ်ရန်
249
198
  */
@@ -306,131 +255,4 @@ const generateUUID = () => {
306
255
  );
307
256
  };
308
257
 
309
- /**
310
- * User Validation Schemas
311
- */
312
- const userSchema = {
313
- // Standard Register Schema
314
- register: Joi.object({
315
- username: Joi.string().alphanum().min(3).max(30).required().messages({
316
- "string.min": "Username must be at least 3 characters long",
317
- "any.required": "Username is a required field",
318
- }),
319
- email: Joi.string()
320
- .email({ minDomainSegments: 2, tlds: { allow: ["com", "net", "org"] } })
321
- .required()
322
- .messages({
323
- "string.email": "Please provide a valid email address",
324
- }),
325
- password: Joi.string().min(8).required().messages({
326
- "string.min": "Password must be at least 8 characters long",
327
- }),
328
- confirmPassword: Joi.any()
329
- .equal(Joi.ref("password"))
330
- .required()
331
- .messages({ "any.only": "Passwords do not match" }),
332
- role: Joi.string().valid("user", "admin").default("user"),
333
- }),
334
-
335
- // Login Schema
336
- login: Joi.object({
337
- email: Joi.string().email().required(),
338
- password: Joi.string().required(),
339
- }),
340
-
341
- // Password Update Schema
342
- updatePassword: Joi.object({
343
- currentPassword: Joi.string().required(),
344
- newPassword: Joi.string().min(8).required(),
345
- }),
346
-
347
- /**
348
- * စိတ်ကြိုက် schema အသစ်ဆောက်ချင်ရင် သုံးရန် (Dynamic Flexibility)
349
- * @param {Object} schemaDefinition - Joi object definition
350
- */
351
- custom: (schemaDefinition) => Joi.object(schemaDefinition),
352
- };
353
-
354
- /**
355
- * Common Joi Schemas
356
- */
357
- const commonSchema = {
358
- // MongoDB ObjectId စစ်ဆေးရန် (24 hex characters)
359
- objectId: Joi.string()
360
- .regex(/^[0-9a-fA-F]{24}$/)
361
- .messages({
362
- "string.pattern.base": "Invalid ID format. Must be a valid ObjectId.",
363
- }),
364
-
365
- // Pagination အတွက် (Query strings)
366
- pagination: Joi.object({
367
- page: Joi.number().integer().min(1).default(1),
368
- limit: Joi.number().integer().min(1).max(100).default(10),
369
- sort: Joi.string().optional(),
370
- fields: Joi.string().optional(),
371
- }),
372
- };
373
-
374
- const schemas = {
375
- user: userSchema,
376
- common: commonSchema,
377
- };
378
-
379
- let io;
380
-
381
- /**
382
- * Socket Authentication Middleware
383
- */
384
- const socketAuth = (secret) => {
385
- return (socket, next) => {
386
- const token =
387
- socket.handshake.auth?.token || socket.handshake.headers?.token;
388
-
389
- if (!token) {
390
- return next(new Error("Authentication error: Token missing"));
391
- }
392
-
393
- try {
394
- const decoded = jwt.verify(token, secret || process.env.JWT_SECRET);
395
- socket.user = decoded; // socket ထဲမှာ user data သိမ်းထားမယ်
396
- next();
397
- } catch (err) {
398
- next(new Error("Authentication error: Invalid token"));
399
- }
400
- };
401
- };
402
-
403
- /**
404
- * Socket Initialize လုပ်ခြင်း
405
- */
406
- const initSocket = (server, options = {}) => {
407
- io = new Server(server, {
408
- cors: {
409
- origin: options.origin || "*",
410
- },
411
- ...options,
412
- });
413
-
414
- // JWT Middleware ကို အသုံးပြုခြင်း
415
- if (options.authRequired) {
416
- io.use(socketAuth(options.jwtSecret));
417
- }
418
-
419
- return io;
420
- };
421
-
422
- /**
423
- * Initialize ပြီးသား IO object ကို ပြန်ယူခြင်း
424
- */
425
- const getIO = () => {
426
- if (!io) throw new Error("Socket.io not initialized!");
427
- return io;
428
- };
429
-
430
- declare const index_getIO: typeof getIO;
431
- declare const index_initSocket: typeof initSocket;
432
- declare namespace index {
433
- export { index_getIO as getIO, index_initSocket as initSocket };
434
- }
435
-
436
- export { AppError, STATUS_CODES, admin, response as apiResponse, auth, catchAsync, comparePassword, connectDB, errorMiddleware, generateToken, generateUUID, hashPassword, schemas, index as socket, validate };
258
+ export { AppError, STATUS_CODES, admin, apiResponse, auth, catchAsync, comparePassword, connectDB, errorMiddleware, generateToken, generateUUID, hashPassword };