response-standardizer 1.0.4 → 1.0.6

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/dist/index.d.ts CHANGED
@@ -15,6 +15,7 @@ export declare const initKeycloak: (config: {
15
15
  service?: string;
16
16
  realm?: string;
17
17
  }) => Promise<void>;
18
- export declare const protect: (allowedRoles?: string[]) => (req: any, res: any, next: any) => void | ((req: any, res: any, next: any) => void);
18
+ export declare const protect: (allowedRoles?: string[]) => (req: any, res: any, next: any) => void;
19
19
  export declare const RestResponse: RestResponseFunctions;
20
20
  export declare const RestMiddleware: RestMiddlewareFunctions;
21
+ export declare const log: (level: "INFO" | "WARN" | "ERROR", message: string, meta?: any) => void;
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { generateRequestId, getTimestamp } from "./utils.js";
2
2
  import axios from "axios";
3
3
  import jwt from "jsonwebtoken";
4
+ import path from "path";
4
5
  let KEYCLOAK_PUBLIC_KEY = null;
5
6
  export const initKeycloak = async (config) => {
6
7
  const KEYCLOAK_SERVICE = config.service ?? "localhost";
@@ -23,7 +24,7 @@ export const protect = (allowedRoles) => {
23
24
  const decoded = jwt.verify(token, KEYCLOAK_PUBLIC_KEY, { algorithms: ["RS256"] });
24
25
  req.user = decoded;
25
26
  if (allowedRoles)
26
- return role(allowedRoles);
27
+ return role(req, res, next, allowedRoles);
27
28
  next();
28
29
  }
29
30
  catch (err) {
@@ -32,24 +33,22 @@ export const protect = (allowedRoles) => {
32
33
  }
33
34
  };
34
35
  };
35
- const role = (allowedRoles) => {
36
- return (req, res, next) => {
37
- const user = req.user;
38
- if (!user) {
39
- return RestResponse.unauthorized(req, res);
40
- }
41
- const realmRoles = (user?.realm_access?.roles ?? []).map((r) => r.toUpperCase());
42
- const clientRoles = Object.values(user?.resource_access ?? {})
43
- .flatMap((r) => r.roles ?? [])
44
- .map((r) => r.toUpperCase());
45
- const allowedUpper = allowedRoles.map(r => r.toUpperCase());
46
- const allRoles = [...realmRoles, ...clientRoles];
47
- const hasAccess = allowedUpper.some((role) => allRoles.includes(role));
48
- if (!hasAccess) {
49
- return RestResponse.accessDenied(req, res);
50
- }
51
- next();
52
- };
36
+ const role = (req, res, next, allowedRoles) => {
37
+ const user = req.user;
38
+ if (!user) {
39
+ return RestResponse.unauthorized(req, res);
40
+ }
41
+ const realmRoles = (user?.realm_access?.roles ?? []).map((r) => r.toUpperCase());
42
+ const clientRoles = Object.values(user?.resource_access ?? {})
43
+ .flatMap((r) => r.roles ?? [])
44
+ .map((r) => r.toUpperCase());
45
+ const allowedUpper = allowedRoles.map(r => r.toUpperCase());
46
+ const allRoles = [...realmRoles, ...clientRoles];
47
+ const hasAccess = allowedUpper.some((role) => allRoles.includes(role));
48
+ if (!hasAccess) {
49
+ return RestResponse.accessDenied(req, res);
50
+ }
51
+ next();
53
52
  };
54
53
  const success = (req, res, data, message = null) => {
55
54
  res.status(200).json({ data, message });
@@ -119,3 +118,38 @@ const responseHandlerMiddleware = (req, res, next) => {
119
118
  export const RestMiddleware = {
120
119
  responseHandlerMiddleware
121
120
  };
121
+ const colors = {
122
+ RESET: "\x1b[0m",
123
+ RED: "\x1b[31m",
124
+ GREEN: "\x1b[32m",
125
+ YELLOW: "\x1b[33m"
126
+ };
127
+ const isProduction = process.env.NODE_ENV === "production";
128
+ export const log = (level, message, meta) => {
129
+ const timestamp = new Date().toISOString();
130
+ // انتخاب رنگ فقط در dev
131
+ let color = colors.RESET;
132
+ if (!isProduction) {
133
+ if (level === "INFO")
134
+ color = colors.GREEN;
135
+ if (level === "WARN")
136
+ color = colors.YELLOW;
137
+ if (level === "ERROR")
138
+ color = colors.RED;
139
+ }
140
+ // گرفتن stack trace
141
+ const stack = new Error().stack?.split("\n")[2]; // خط Caller
142
+ let location = "";
143
+ if (stack) {
144
+ const match = stack.match(/\((.*):(\d+):(\d+)\)/);
145
+ if (match) {
146
+ const fileName = path.basename(match[1]);
147
+ const line = match[2];
148
+ const column = match[3];
149
+ location = `${fileName}:${line}:${column}`;
150
+ }
151
+ }
152
+ const metaStr = meta ? `. ${JSON.stringify(meta)}` : "";
153
+ // چاپ لاگ
154
+ console.log(`${color}[${timestamp}][${location}][${level}] ${message}${metaStr}${colors.RESET}`);
155
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "response-standardizer",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "Express middleware to standardize API responses",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@ import { ErrorFields, PaginationMeta, StandardResponse, RestResponseFunctions, R
3
3
  import { generateRequestId, getTimestamp } from "./utils.js";
4
4
  import axios from "axios";
5
5
  import jwt from "jsonwebtoken";
6
+ import path from "path";
6
7
  declare global {
7
8
  namespace Express {
8
9
  interface Response {
@@ -40,7 +41,7 @@ export const protect = (allowedRoles?: string[]) => {
40
41
  const decoded = jwt.verify(token, KEYCLOAK_PUBLIC_KEY, { algorithms: ["RS256"] });
41
42
  (req as any).user = decoded;
42
43
  if(allowedRoles)
43
- return role(allowedRoles);
44
+ return role(req, res, next, allowedRoles);
44
45
 
45
46
  next();
46
47
  } catch (err) {
@@ -50,9 +51,8 @@ export const protect = (allowedRoles?: string[]) => {
50
51
  }
51
52
 
52
53
  }
53
- const role = (allowedRoles: string[]) => {
54
- return (req: any, res: any, next: any) => {
55
- const user = req.user;
54
+ const role = (req: any, res: any, next: any, allowedRoles: string[]) => {
55
+ const user = req.user;
56
56
  if (!user) {
57
57
  return RestResponse.unauthorized(req, res);
58
58
  }
@@ -69,8 +69,6 @@ const role = (allowedRoles: string[]) => {
69
69
  return RestResponse.accessDenied(req, res)
70
70
  }
71
71
  next()
72
- }
73
-
74
72
  }
75
73
  const success = <T>(req: Request, res: Response, data: T, message: string | null = null) => {
76
74
  res.status(200).json({ data, message });
@@ -176,4 +174,44 @@ const responseHandlerMiddleware = (
176
174
 
177
175
  export const RestMiddleware: RestMiddlewareFunctions = {
178
176
  responseHandlerMiddleware
179
- }
177
+ }
178
+
179
+
180
+ const colors = {
181
+ RESET: "\x1b[0m",
182
+ RED: "\x1b[31m",
183
+ GREEN: "\x1b[32m",
184
+ YELLOW: "\x1b[33m"
185
+ };
186
+
187
+ const isProduction = process.env.NODE_ENV === "production";
188
+
189
+ export const log = (level: "INFO" | "WARN" | "ERROR", message: string, meta?: any) => {
190
+ const timestamp = new Date().toISOString();
191
+
192
+ // انتخاب رنگ فقط در dev
193
+ let color = colors.RESET;
194
+ if (!isProduction) {
195
+ if (level === "INFO") color = colors.GREEN;
196
+ if (level === "WARN") color = colors.YELLOW;
197
+ if (level === "ERROR") color = colors.RED;
198
+ }
199
+
200
+ // گرفتن stack trace
201
+ const stack = new Error().stack?.split("\n")[2]; // خط Caller
202
+ let location = "";
203
+ if (stack) {
204
+ const match = stack.match(/\((.*):(\d+):(\d+)\)/);
205
+ if (match) {
206
+ const fileName = path.basename(match[1]);
207
+ const line = match[2];
208
+ const column = match[3];
209
+ location = `${fileName}:${line}:${column}`;
210
+ }
211
+ }
212
+
213
+ const metaStr = meta ? `. ${JSON.stringify(meta)}` : "";
214
+
215
+ // چاپ لاگ
216
+ console.log(`${color}[${timestamp}][${location}][${level}] ${message}${metaStr}${colors.RESET}`);
217
+ };