@catbee/utils 0.0.1 → 0.0.3
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 +303 -107
- package/build/esm/config.d.ts +13 -1
- package/build/esm/config.js +16 -4
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +20 -18
- package/build/esm/index.js +20 -18
- package/build/esm/index.js.map +1 -1
- package/build/esm/types/api-response.d.ts +83 -1
- package/build/esm/types/api-response.js.map +1 -1
- package/build/esm/utils/array.utils.d.ts +65 -2
- package/build/esm/utils/array.utils.js +147 -20
- package/build/esm/utils/array.utils.js.map +1 -1
- package/build/esm/utils/async.utils.d.ts +56 -1
- package/build/esm/utils/async.utils.js +166 -11
- package/build/esm/utils/async.utils.js.map +1 -1
- package/build/esm/utils/cache.utils.d.ts +67 -4
- package/build/esm/utils/cache.utils.js +210 -28
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +102 -1
- package/build/esm/utils/context-store.utils.js +185 -3
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.d.ts +110 -8
- package/build/esm/utils/crypto.utils.js +298 -23
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +40 -0
- package/build/esm/utils/decorators.utils.js +312 -0
- package/build/esm/utils/decorators.utils.js.map +1 -0
- package/build/esm/utils/dir.utils.d.ts +122 -1
- package/build/esm/utils/dir.utils.js +578 -3
- package/build/esm/utils/dir.utils.js.map +1 -1
- package/build/esm/utils/env.utils.d.ts +83 -0
- package/build/esm/utils/env.utils.js +235 -6
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/exception.utils.d.ts +117 -1
- package/build/esm/utils/exception.utils.js +331 -12
- package/build/esm/utils/exception.utils.js.map +1 -1
- package/build/esm/utils/fs.utils.d.ts +132 -0
- package/build/esm/utils/fs.utils.js +421 -4
- package/build/esm/utils/fs.utils.js.map +1 -1
- package/build/esm/utils/http-status-codes.d.ts +87 -178
- package/build/esm/utils/http-status-codes.js +92 -178
- package/build/esm/utils/http-status-codes.js.map +1 -1
- package/build/esm/utils/id.utils.d.ts +11 -10
- package/build/esm/utils/id.utils.js +30 -21
- package/build/esm/utils/id.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +35 -2
- package/build/esm/utils/logger.utils.js +68 -14
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +73 -0
- package/build/esm/utils/middleware.utils.js +158 -0
- package/build/esm/utils/middleware.utils.js.map +1 -0
- package/build/esm/utils/obj.utils.d.ts +65 -3
- package/build/esm/utils/obj.utils.js +206 -18
- package/build/esm/utils/obj.utils.js.map +1 -1
- package/build/esm/utils/response.utils.d.ts +103 -2
- package/build/esm/utils/response.utils.js +156 -3
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esm/utils/string.utils.d.ts +61 -5
- package/build/esm/utils/string.utils.js +109 -19
- package/build/esm/utils/string.utils.js.map +1 -1
- package/build/esm/utils/url.utils.d.ts +117 -0
- package/build/esm/utils/url.utils.js +287 -2
- package/build/esm/utils/url.utils.js.map +1 -1
- package/build/esm/utils/validate.utils.d.ts +110 -0
- package/build/esm/utils/validate.utils.js +190 -8
- package/build/esm/utils/validate.utils.js.map +1 -1
- package/build/esnext/config.d.ts +13 -1
- package/build/esnext/config.js +16 -4
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +20 -18
- package/build/esnext/index.js +20 -18
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/types/api-response.d.ts +83 -1
- package/build/esnext/types/api-response.js.map +1 -1
- package/build/esnext/utils/array.utils.d.ts +65 -2
- package/build/esnext/utils/array.utils.js +140 -21
- package/build/esnext/utils/array.utils.js.map +1 -1
- package/build/esnext/utils/async.utils.d.ts +56 -1
- package/build/esnext/utils/async.utils.js +130 -14
- package/build/esnext/utils/async.utils.js.map +1 -1
- package/build/esnext/utils/cache.utils.d.ts +67 -4
- package/build/esnext/utils/cache.utils.js +137 -9
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +102 -1
- package/build/esnext/utils/context-store.utils.js +171 -3
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.d.ts +110 -8
- package/build/esnext/utils/crypto.utils.js +199 -19
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +40 -0
- package/build/esnext/utils/decorators.utils.js +155 -0
- package/build/esnext/utils/decorators.utils.js.map +1 -0
- package/build/esnext/utils/dir.utils.d.ts +122 -1
- package/build/esnext/utils/dir.utils.js +307 -3
- package/build/esnext/utils/dir.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.d.ts +83 -0
- package/build/esnext/utils/env.utils.js +191 -8
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/exception.utils.d.ts +117 -1
- package/build/esnext/utils/exception.utils.js +222 -12
- package/build/esnext/utils/exception.utils.js.map +1 -1
- package/build/esnext/utils/fs.utils.d.ts +132 -0
- package/build/esnext/utils/fs.utils.js +268 -4
- package/build/esnext/utils/fs.utils.js.map +1 -1
- package/build/esnext/utils/http-status-codes.d.ts +87 -178
- package/build/esnext/utils/http-status-codes.js +92 -178
- package/build/esnext/utils/http-status-codes.js.map +1 -1
- package/build/esnext/utils/id.utils.d.ts +11 -10
- package/build/esnext/utils/id.utils.js +28 -20
- package/build/esnext/utils/id.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +35 -2
- package/build/esnext/utils/logger.utils.js +56 -14
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +73 -0
- package/build/esnext/utils/middleware.utils.js +157 -0
- package/build/esnext/utils/middleware.utils.js.map +1 -0
- package/build/esnext/utils/obj.utils.d.ts +65 -3
- package/build/esnext/utils/obj.utils.js +169 -14
- package/build/esnext/utils/obj.utils.js.map +1 -1
- package/build/esnext/utils/response.utils.d.ts +103 -2
- package/build/esnext/utils/response.utils.js +141 -3
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/esnext/utils/string.utils.d.ts +61 -5
- package/build/esnext/utils/string.utils.js +110 -14
- package/build/esnext/utils/string.utils.js.map +1 -1
- package/build/esnext/utils/url.utils.d.ts +117 -0
- package/build/esnext/utils/url.utils.js +248 -2
- package/build/esnext/utils/url.utils.js.map +1 -1
- package/build/esnext/utils/validate.utils.d.ts +110 -0
- package/build/esnext/utils/validate.utils.js +190 -8
- package/build/esnext/utils/validate.utils.js.map +1 -1
- package/build/src/config.d.ts +13 -1
- package/build/src/config.js +15 -3
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +20 -18
- package/build/src/index.js +2 -0
- package/build/src/index.js.map +1 -1
- package/build/src/types/api-response.d.ts +83 -1
- package/build/src/types/api-response.js.map +1 -1
- package/build/src/utils/array.utils.d.ts +65 -2
- package/build/src/utils/array.utils.js +147 -22
- package/build/src/utils/array.utils.js.map +1 -1
- package/build/src/utils/async.utils.d.ts +56 -1
- package/build/src/utils/async.utils.js +137 -17
- package/build/src/utils/async.utils.js.map +1 -1
- package/build/src/utils/cache.utils.d.ts +67 -4
- package/build/src/utils/cache.utils.js +137 -9
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +102 -1
- package/build/src/utils/context-store.utils.js +173 -3
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.d.ts +110 -8
- package/build/src/utils/crypto.utils.js +214 -27
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +40 -0
- package/build/src/utils/decorators.utils.js +165 -0
- package/build/src/utils/decorators.utils.js.map +1 -0
- package/build/src/utils/dir.utils.d.ts +122 -1
- package/build/src/utils/dir.utils.js +314 -0
- package/build/src/utils/dir.utils.js.map +1 -1
- package/build/src/utils/env.utils.d.ts +83 -0
- package/build/src/utils/env.utils.js +192 -9
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/exception.utils.d.ts +117 -1
- package/build/src/utils/exception.utils.js +233 -11
- package/build/src/utils/exception.utils.js.map +1 -1
- package/build/src/utils/fs.utils.d.ts +132 -0
- package/build/src/utils/fs.utils.js +281 -3
- package/build/src/utils/fs.utils.js.map +1 -1
- package/build/src/utils/http-status-codes.d.ts +87 -178
- package/build/src/utils/http-status-codes.js +92 -178
- package/build/src/utils/http-status-codes.js.map +1 -1
- package/build/src/utils/id.utils.d.ts +11 -10
- package/build/src/utils/id.utils.js +28 -20
- package/build/src/utils/id.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +35 -2
- package/build/src/utils/logger.utils.js +56 -11
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +73 -0
- package/build/src/utils/middleware.utils.js +163 -0
- package/build/src/utils/middleware.utils.js.map +1 -0
- package/build/src/utils/obj.utils.d.ts +65 -3
- package/build/src/utils/obj.utils.js +179 -18
- package/build/src/utils/obj.utils.js.map +1 -1
- package/build/src/utils/response.utils.d.ts +103 -2
- package/build/src/utils/response.utils.js +147 -2
- package/build/src/utils/response.utils.js.map +1 -1
- package/build/src/utils/string.utils.d.ts +61 -5
- package/build/src/utils/string.utils.js +122 -20
- package/build/src/utils/string.utils.js.map +1 -1
- package/build/src/utils/url.utils.d.ts +117 -0
- package/build/src/utils/url.utils.js +256 -1
- package/build/src/utils/url.utils.js.map +1 -1
- package/build/src/utils/validate.utils.d.ts +110 -0
- package/build/src/utils/validate.utils.js +204 -8
- package/build/src/utils/validate.utils.js.map +1 -1
- package/package.json +20 -12
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import { randomUUID } from
|
|
2
|
-
import { ulid } from "ulid";
|
|
3
|
-
import { nanoid } from "nanoid";
|
|
1
|
+
import { randomUUID, randomBytes } from 'crypto';
|
|
4
2
|
/**
|
|
5
3
|
* Generates a UUID v4 string (RFC 4122).
|
|
6
4
|
*
|
|
@@ -10,22 +8,22 @@ export function uuid() {
|
|
|
10
8
|
return randomUUID();
|
|
11
9
|
}
|
|
12
10
|
/**
|
|
13
|
-
* Generates a
|
|
11
|
+
* Generates a nanoid-style random ID (URL-safe, customizable length).
|
|
14
12
|
*
|
|
15
|
-
* @
|
|
13
|
+
* @param {number} length - Length of the ID (default: 21).
|
|
14
|
+
* @returns {string} Nanoid-style random string.
|
|
16
15
|
*/
|
|
17
|
-
export function
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
return nanoid(size);
|
|
16
|
+
export function nanoId(length) {
|
|
17
|
+
if (length === void 0) { length = 21; }
|
|
18
|
+
if (length <= 0)
|
|
19
|
+
return '';
|
|
20
|
+
var id = '';
|
|
21
|
+
while (id.length < length) {
|
|
22
|
+
id += randomBytes(Math.ceil((length * 3) / 4))
|
|
23
|
+
.toString('base64url')
|
|
24
|
+
.replace(/[+/=]/g, '');
|
|
25
|
+
}
|
|
26
|
+
return id.slice(0, length);
|
|
29
27
|
}
|
|
30
28
|
/**
|
|
31
29
|
* Generates a cryptographically strong random hex string.
|
|
@@ -35,10 +33,11 @@ export function nanoId(size) {
|
|
|
35
33
|
*/
|
|
36
34
|
export function randomHex(byteLength) {
|
|
37
35
|
if (byteLength === void 0) { byteLength = 16; }
|
|
38
|
-
// Node
|
|
39
|
-
//
|
|
40
|
-
return
|
|
41
|
-
.toString(
|
|
36
|
+
// Use Node.js crypto for both Node and browser compatibility
|
|
37
|
+
// Prefer randomBytes if available (Node), fallback to getRandomValues for browser (not used here)
|
|
38
|
+
return randomBytes(byteLength)
|
|
39
|
+
.toString('hex')
|
|
40
|
+
.padStart(byteLength * 2, '0')
|
|
42
41
|
.slice(0, byteLength * 2);
|
|
43
42
|
}
|
|
44
43
|
/**
|
|
@@ -52,4 +51,14 @@ export function randomInt(min, max) {
|
|
|
52
51
|
var range = max - min + 1;
|
|
53
52
|
return Math.floor(Math.random() * range) + min;
|
|
54
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* Generates a cryptographically strong random base64 string.
|
|
56
|
+
*
|
|
57
|
+
* @param {number} byteLength - Number of random bytes (default: 16).
|
|
58
|
+
* @returns {string} Random base64 string (URL-safe, no padding).
|
|
59
|
+
*/
|
|
60
|
+
export function randomBase64(byteLength) {
|
|
61
|
+
if (byteLength === void 0) { byteLength = 16; }
|
|
62
|
+
return randomBytes(byteLength).toString('base64url');
|
|
63
|
+
}
|
|
55
64
|
//# sourceMappingURL=id.utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"id.utils.js","sourceRoot":"","sources":["../../../src/utils/id.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,
|
|
1
|
+
{"version":3,"file":"id.utils.js","sourceRoot":"","sources":["../../../src/utils/id.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAEjD;;;;GAIG;AACH,MAAM,UAAU,IAAI;IAClB,OAAO,UAAU,EAAE,CAAC;AACtB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,MAAM,CAAC,MAAmB;IAAnB,uBAAA,EAAA,WAAmB;IACxC,IAAI,MAAM,IAAI,CAAC;QAAE,OAAO,EAAE,CAAC;IAC3B,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,OAAO,EAAE,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC;QAC1B,EAAE,IAAI,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;aAC3C,QAAQ,CAAC,WAAW,CAAC;aACrB,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAC3B,CAAC;IACD,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AAC7B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,UAAuB;IAAvB,2BAAA,EAAA,eAAuB;IAC/C,6DAA6D;IAC7D,kGAAkG;IAClG,OAAO,WAAW,CAAC,UAAU,CAAC;SAC3B,QAAQ,CAAC,KAAK,CAAC;SACf,QAAQ,CAAC,UAAU,GAAG,CAAC,EAAE,GAAG,CAAC;SAC7B,KAAK,CAAC,CAAC,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,GAAW,EAAE,GAAW;IAChD,IAAM,KAAK,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;IAC5B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC;AACjD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,UAAuB;IAAvB,2BAAA,EAAA,eAAuB;IAClD,OAAO,WAAW,CAAC,UAAU,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AACvD,CAAC","sourcesContent":["import { randomUUID, randomBytes } from 'crypto';\n\n/**\n * Generates a UUID v4 string (RFC 4122).\n *\n * @returns {string} UUID v4 (e.g., 'c0de1234-5678-9abc-def0-123456789abc')\n */\nexport function uuid(): string {\n return randomUUID();\n}\n\n/**\n * Generates a nanoid-style random ID (URL-safe, customizable length).\n *\n * @param {number} length - Length of the ID (default: 21).\n * @returns {string} Nanoid-style random string.\n */\nexport function nanoId(length: number = 21): string {\n if (length <= 0) return '';\n let id = '';\n while (id.length < length) {\n id += randomBytes(Math.ceil((length * 3) / 4))\n .toString('base64url')\n .replace(/[+/=]/g, '');\n }\n return id.slice(0, length);\n}\n\n/**\n * Generates a cryptographically strong random hex string.\n *\n * @param {number} byteLength - Number of random bytes (default: 16 → 32 hex chars).\n * @returns {string} Random hex string.\n */\nexport function randomHex(byteLength: number = 16): string {\n // Use Node.js crypto for both Node and browser compatibility\n // Prefer randomBytes if available (Node), fallback to getRandomValues for browser (not used here)\n return randomBytes(byteLength)\n .toString('hex')\n .padStart(byteLength * 2, '0')\n .slice(0, byteLength * 2);\n}\n\n/**\n * Generates a random integer between min (inclusive) and max (inclusive).\n *\n * @param {number} min - Minimum value.\n * @param {number} max - Maximum value.\n * @returns {number} Random integer in range.\n */\nexport function randomInt(min: number, max: number): number {\n const range = max - min + 1;\n return Math.floor(Math.random() * range) + min;\n}\n\n/**\n * Generates a cryptographically strong random base64 string.\n *\n * @param {number} byteLength - Number of random bytes (default: 16).\n * @returns {string} Random base64 string (URL-safe, no padding).\n */\nexport function randomBase64(byteLength: number = 16): string {\n return randomBytes(byteLength).toString('base64url');\n}\n"]}
|
|
@@ -1,4 +1,13 @@
|
|
|
1
|
-
import
|
|
1
|
+
import pino from 'pino';
|
|
2
|
+
import type { Logger as PinoLogger } from 'pino';
|
|
3
|
+
/**
|
|
4
|
+
* Logger type for application-wide logging.
|
|
5
|
+
*/
|
|
6
|
+
export type Logger = pino.Logger;
|
|
7
|
+
/**
|
|
8
|
+
* Logger levels for application-wide logging.
|
|
9
|
+
*/
|
|
10
|
+
export type LoggerLevels = pino.Level;
|
|
2
11
|
/**
|
|
3
12
|
* Use an object compatible with either modern or legacy global scopes.
|
|
4
13
|
*/
|
|
@@ -11,5 +20,29 @@ export declare const _globalThis: typeof globalThis;
|
|
|
11
20
|
*
|
|
12
21
|
* @returns {Logger} The logger instance (request-bound or global root logger)
|
|
13
22
|
*/
|
|
14
|
-
export declare function getLogger():
|
|
23
|
+
export declare function getLogger(): PinoLogger;
|
|
24
|
+
/**
|
|
25
|
+
* Creates a child logger with additional context.
|
|
26
|
+
*
|
|
27
|
+
* @param {Record<string, any>} bindings - Properties to attach to all log records
|
|
28
|
+
* @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)
|
|
29
|
+
* @returns {Logger} Child logger with merged context
|
|
30
|
+
*/
|
|
31
|
+
export declare function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger;
|
|
32
|
+
/**
|
|
33
|
+
* Creates a request-scoped logger with request ID and stores it in context
|
|
34
|
+
*
|
|
35
|
+
* @param {string} requestId - Unique request identifier
|
|
36
|
+
* @param {object} [additionalContext] - Additional context to include in logs
|
|
37
|
+
* @returns {Logger} Request-scoped logger instance
|
|
38
|
+
*/
|
|
39
|
+
export declare function createRequestLogger(requestId: string, additionalContext?: Record<string, any>): PinoLogger;
|
|
40
|
+
/**
|
|
41
|
+
* Utility to safely log errors with proper stack trace extraction
|
|
42
|
+
*
|
|
43
|
+
* @param {Error|unknown} error - Error object to log
|
|
44
|
+
* @param {string} [message] - Optional message to include
|
|
45
|
+
* @param {Record<string, any>} [context] - Additional context properties
|
|
46
|
+
*/
|
|
47
|
+
export declare function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void;
|
|
15
48
|
//# sourceMappingURL=logger.utils.d.ts.map
|
|
@@ -1,14 +1,25 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
var __assign = (this && this.__assign) || function () {
|
|
2
|
+
__assign = Object.assign || function(t) {
|
|
3
|
+
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
|
4
|
+
s = arguments[i];
|
|
5
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
|
|
6
|
+
t[p] = s[p];
|
|
7
|
+
}
|
|
8
|
+
return t;
|
|
9
|
+
};
|
|
10
|
+
return __assign.apply(this, arguments);
|
|
11
|
+
};
|
|
12
|
+
import pino, { stdTimeFunctions } from 'pino';
|
|
13
|
+
import { Config } from '../config';
|
|
14
|
+
import { ContextStore, StoreKeys } from './context-store.utils';
|
|
4
15
|
/**
|
|
5
16
|
* Symbol used to store the root logger in the Node.js global object.
|
|
6
17
|
*/
|
|
7
|
-
var GLOBAL_LOGGER_KEY = Symbol.for(
|
|
18
|
+
var GLOBAL_LOGGER_KEY = Symbol.for('logger');
|
|
8
19
|
/**
|
|
9
20
|
* Use an object compatible with either modern or legacy global scopes.
|
|
10
21
|
*/
|
|
11
|
-
export var _globalThis = typeof globalThis ===
|
|
22
|
+
export var _globalThis = typeof globalThis === 'object' ? globalThis : global;
|
|
12
23
|
var _global = _globalThis;
|
|
13
24
|
/**
|
|
14
25
|
* Initializes the global root logger according to app configuration.
|
|
@@ -21,23 +32,23 @@ function setupLogger() {
|
|
|
21
32
|
name: Config.Logger.name,
|
|
22
33
|
level: Config.Logger.level,
|
|
23
34
|
redact: {
|
|
24
|
-
paths: [
|
|
35
|
+
paths: ['req.authorization', 'url'],
|
|
25
36
|
censor: function (value, path) {
|
|
26
|
-
if (path[0] ===
|
|
27
|
-
return value.replace(/access_token=[a-zA-Z0-9_-]*/,
|
|
37
|
+
if (path[0] === 'url') {
|
|
38
|
+
return value.replace(/access_token=[a-zA-Z0-9_-]*/, 'access_token=***');
|
|
28
39
|
}
|
|
29
|
-
else if (path[1] ===
|
|
30
|
-
return value.replace(/\s+(\S+)$/,
|
|
40
|
+
else if (path[1] === 'authorization') {
|
|
41
|
+
return value.replace(/\s+(\S+)$/, ' ***');
|
|
31
42
|
}
|
|
32
|
-
return
|
|
33
|
-
}
|
|
34
|
-
}
|
|
43
|
+
return '***';
|
|
44
|
+
}
|
|
45
|
+
}
|
|
35
46
|
};
|
|
36
47
|
if (Config.Logger.isoTimestamp) {
|
|
37
48
|
logParams.timestamp = stdTimeFunctions.isoTime;
|
|
38
49
|
}
|
|
39
50
|
_global[GLOBAL_LOGGER_KEY] = pino(logParams);
|
|
40
|
-
_global[GLOBAL_LOGGER_KEY].debug(
|
|
51
|
+
_global[GLOBAL_LOGGER_KEY].debug('Logger initialized');
|
|
41
52
|
}
|
|
42
53
|
/**
|
|
43
54
|
* Retrieves the current logger instance:
|
|
@@ -56,4 +67,47 @@ export function getLogger() {
|
|
|
56
67
|
}
|
|
57
68
|
return _global[GLOBAL_LOGGER_KEY];
|
|
58
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* Creates a child logger with additional context.
|
|
72
|
+
*
|
|
73
|
+
* @param {Record<string, any>} bindings - Properties to attach to all log records
|
|
74
|
+
* @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)
|
|
75
|
+
* @returns {Logger} Child logger with merged context
|
|
76
|
+
*/
|
|
77
|
+
export function createChildLogger(bindings, parentLogger) {
|
|
78
|
+
var logger = parentLogger || getLogger();
|
|
79
|
+
return logger.child(bindings);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Creates a request-scoped logger with request ID and stores it in context
|
|
83
|
+
*
|
|
84
|
+
* @param {string} requestId - Unique request identifier
|
|
85
|
+
* @param {object} [additionalContext] - Additional context to include in logs
|
|
86
|
+
* @returns {Logger} Request-scoped logger instance
|
|
87
|
+
*/
|
|
88
|
+
export function createRequestLogger(requestId, additionalContext) {
|
|
89
|
+
if (additionalContext === void 0) { additionalContext = {}; }
|
|
90
|
+
var logger = createChildLogger(__assign({ requestId: requestId }, additionalContext));
|
|
91
|
+
try {
|
|
92
|
+
ContextStore.set(StoreKeys.LOGGER, logger);
|
|
93
|
+
}
|
|
94
|
+
catch (_a) {
|
|
95
|
+
// Context not initialized, can't store logger
|
|
96
|
+
logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');
|
|
97
|
+
}
|
|
98
|
+
return logger;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Utility to safely log errors with proper stack trace extraction
|
|
102
|
+
*
|
|
103
|
+
* @param {Error|unknown} error - Error object to log
|
|
104
|
+
* @param {string} [message] - Optional message to include
|
|
105
|
+
* @param {Record<string, any>} [context] - Additional context properties
|
|
106
|
+
*/
|
|
107
|
+
export function logError(error, message, context) {
|
|
108
|
+
var logger = getLogger();
|
|
109
|
+
var errObj = error instanceof Error ? error : new Error(String(error));
|
|
110
|
+
var logContext = __assign(__assign({}, context), { err: errObj });
|
|
111
|
+
logger.error(logContext, message || errObj.message);
|
|
112
|
+
}
|
|
59
113
|
//# sourceMappingURL=logger.utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,EAAE,EAAiB,gBAAgB,EAAE,MAAM,MAAM,CAAC;AAE7D,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAEhE;;GAEG;AACH,IAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"logger.utils.js","sourceRoot":"","sources":["../../../src/utils/logger.utils.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,IAAI,EAAE,EAAiB,gBAAgB,EAAE,MAAM,MAAM,CAAC;AAE7D,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAEhE;;GAEG;AACH,IAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AAY/C;;GAEG;AACH,MAAM,CAAC,IAAM,WAAW,GAAG,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC;AAChF,IAAM,OAAO,GAAG,WAA6D,CAAC;AAE9E;;;;;GAKG;AACH,SAAS,WAAW;IAClB,IAAM,SAAS,GAAkB;QAC/B,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI;QACxB,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,KAAK;QAC1B,MAAM,EAAE;YACN,KAAK,EAAE,CAAC,mBAAmB,EAAE,KAAK,CAAC;YACnC,MAAM,YAAC,KAAK,EAAE,IAAI;gBAChB,IAAI,I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AiB,YAC9B,SAAS,WAAA,IACN,iBAAiB,EACpB,CAAC;IAEH,IAAI,CAAC;QACH,YAAY,CAAC,GAAG,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7C,CAAC;IAAC,WAAM,CAAC;QACP,8CAA8C;QAC9C,MAAM,CAAC,KAAK,CAAC,uEAAuE,CAAC,CAAC;IACxF,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,QAAQ,CAAC,KAAsB,EAAE,OAAgB,EAAE,OAA6B;IAC9F,IAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAE3B,IAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACzE,IAAM,UAAU,yBACX,OAAO,KACV,GAAG,EAAE,MAAM,GACZ,CAAC;IAEF,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AACtD,CAAC","sourcesContent":["import pino, { LoggerOptions, stdTimeFunctions } from 'pino';\nimport type { Logger as PinoLogger } from 'pino'; // Type-only import\nimport { Config } from '../config';\nimport { ContextStore, StoreKeys } from './context-store.utils';\n\n/**\n * Symbol used to store the root logger in the Node.js global object.\n */\nconst GLOBAL_LOGGER_KEY = Symbol.for('logger');\n\n/**\n * Logger type for application-wide logging.\n */\nexport type Logger = pino.Logger;\n\n/**\n * Logger levels for application-wide logging.\n */\nexport type LoggerLevels = pino.Level;\n\n/**\n * Use an object compatible with either modern or legacy global scopes.\n */\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\nconst _global = _globalThis as unknown as { [GLOBAL_LOGGER_KEY]: PinoLogger };\n\n/**\n * Initializes the global root logger according to app configuration.\n *\n * - Sets log name, level, timestamp, and redaction for sensitive fields.\n * - Uses singleton in global symbol registry.\n */\nfunction setupLogger(): void {\n const logParams: LoggerOptions = {\n name: Config.Logger.name,\n level: Config.Logger.level,\n redact: {\n paths: ['req.authorization', 'url'],\n censor(value, path) {\n if (path[0] === 'url') {\n return value.replace(/access_token=[a-zA-Z0-9_-]*/, 'access_token=***');\n } else if (path[1] === 'authorization') {\n return value.replace(/\\s+(\\S+)$/, ' ***');\n }\n return '***';\n }\n }\n };\n\n if (Config.Logger.isoTimestamp) {\n logParams.timestamp = stdTimeFunctions.isoTime;\n }\n\n _global[GLOBAL_LOGGER_KEY] = pino(logParams);\n _global[GLOBAL_LOGGER_KEY].debug('Logger initialized');\n}\n\n/**\n * Retrieves the current logger instance:\n * - Returns a request-scoped logger from AsyncLocalStorage if available\n * - Falls back to the global (singleton) logger\n * - Initializes the global logger if not created yet\n *\n * @returns {Logger} The logger instance (request-bound or global root logger)\n */\nexport function getLogger(): PinoLogger {\n const logger = ContextStore.get<PinoLogger>(StoreKeys.LOGGER);\n if (logger) return logger;\n\n if (!_global[GLOBAL_LOGGER_KEY]) {\n setupLogger();\n }\n\n return _global[GLOBAL_LOGGER_KEY];\n}\n\n/**\n * Creates a child logger with additional context.\n *\n * @param {Record<string, any>} bindings - Properties to attach to all log records\n * @param {Logger} [parentLogger] - Parent logger (defaults to current context logger or global)\n * @returns {Logger} Child logger with merged context\n */\nexport function createChildLogger(bindings: Record<string, any>, parentLogger?: PinoLogger): PinoLogger {\n const logger = parentLogger || getLogger();\n return logger.child(bindings);\n}\n\n/**\n * Creates a request-scoped logger with request ID and stores it in context\n *\n * @param {string} requestId - Unique request identifier\n * @param {object} [additionalContext] - Additional context to include in logs\n * @returns {Logger} Request-scoped logger instance\n */\nexport function createRequestLogger(requestId: string, additionalContext: Record<string, any> = {}): PinoLogger {\n const logger = createChildLogger({\n requestId,\n ...additionalContext\n });\n\n try {\n ContextStore.set(StoreKeys.LOGGER, logger);\n } catch {\n // Context not initialized, can't store logger\n logger.debug('Failed to store logger in context - AsyncLocalStorage not initialized');\n }\n\n return logger;\n}\n\n/**\n * Utility to safely log errors with proper stack trace extraction\n *\n * @param {Error|unknown} error - Error object to log\n * @param {string} [message] - Optional message to include\n * @param {Record<string, any>} [context] - Additional context properties\n */\nexport function logError(error: Error | unknown, message?: string, context?: Record<string, any>): void {\n const logger = getLogger();\n\n const errObj = error instanceof Error ? error : new Error(String(error));\n const logContext = {\n ...context,\n err: errObj\n };\n\n logger.error(logContext, message || errObj.message);\n}\n"]}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type definitions for Express-compatible middleware
|
|
3
|
+
*/
|
|
4
|
+
type Request = {
|
|
5
|
+
headers: Record<string, string | string[] | undefined>;
|
|
6
|
+
method: string;
|
|
7
|
+
url: string;
|
|
8
|
+
ip?: string;
|
|
9
|
+
body?: any;
|
|
10
|
+
query?: Record<string, any>;
|
|
11
|
+
params?: Record<string, any>;
|
|
12
|
+
[key: string]: any;
|
|
13
|
+
};
|
|
14
|
+
type Response = {
|
|
15
|
+
status: (code: number) => Response;
|
|
16
|
+
json: (data: any) => void;
|
|
17
|
+
send: (data: any) => void;
|
|
18
|
+
setHeader: (name: string, value: string | string[]) => void;
|
|
19
|
+
end: (data?: any) => void;
|
|
20
|
+
on: (event: string, callback: (...args: any[]) => void) => void;
|
|
21
|
+
[key: string]: any;
|
|
22
|
+
};
|
|
23
|
+
type NextFunction = (err?: Error | any) => void;
|
|
24
|
+
type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
|
|
25
|
+
/**
|
|
26
|
+
* Attaches a unique request ID to each request.
|
|
27
|
+
* Useful for request tracing and correlation between logs.
|
|
28
|
+
*
|
|
29
|
+
* @param {object} [options] - Configuration options
|
|
30
|
+
* @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
|
|
31
|
+
* @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
|
|
32
|
+
* @returns {Middleware} Express-compatible middleware
|
|
33
|
+
*/
|
|
34
|
+
export declare function requestId(options?: {
|
|
35
|
+
headerName?: string;
|
|
36
|
+
exposeHeader?: boolean;
|
|
37
|
+
}): Middleware;
|
|
38
|
+
/**
|
|
39
|
+
* Measures request processing time and logs or adds it to response headers.
|
|
40
|
+
*
|
|
41
|
+
* @param {object} [options] - Configuration options
|
|
42
|
+
* @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
|
|
43
|
+
* @param {boolean} [options.logOnComplete=false] - Whether to log timing info
|
|
44
|
+
* @returns {Middleware} Express-compatible middleware
|
|
45
|
+
*/
|
|
46
|
+
export declare function responseTime(options?: {
|
|
47
|
+
addHeader?: boolean;
|
|
48
|
+
logOnComplete?: boolean;
|
|
49
|
+
}): Middleware;
|
|
50
|
+
/**
|
|
51
|
+
* Request timeout middleware.
|
|
52
|
+
* Aborts requests that take too long to process.
|
|
53
|
+
*
|
|
54
|
+
* @param {number} [timeoutMs=30000] - Timeout in milliseconds
|
|
55
|
+
* @returns {Middleware} Express-compatible middleware
|
|
56
|
+
*/
|
|
57
|
+
export declare function timeout(timeoutMs?: number): Middleware;
|
|
58
|
+
/**
|
|
59
|
+
* Global error handling middleware with enhanced features.
|
|
60
|
+
*
|
|
61
|
+
* @param {object} [options] - Error handler options
|
|
62
|
+
* @param {boolean} [options.logErrors=true] - Whether to log errors
|
|
63
|
+
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
|
|
64
|
+
* @param {Function} [options.logger=getLogger().error] - Custom logging function
|
|
65
|
+
* @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware
|
|
66
|
+
*/
|
|
67
|
+
export declare function errorHandler(options?: {
|
|
68
|
+
logErrors?: boolean;
|
|
69
|
+
includeDetails?: boolean;
|
|
70
|
+
logger?: (message: string, error: any) => void;
|
|
71
|
+
}): (err: any, req: Request, res: Response, _next: NextFunction) => void;
|
|
72
|
+
export {};
|
|
73
|
+
//# sourceMappingURL=middleware.utils.d.ts.map
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import { Config } from '../config';
|
|
3
|
+
import { uuid } from './id.utils';
|
|
4
|
+
import { HttpStatusCodes } from './http-status-codes';
|
|
5
|
+
import { ErrorResponse } from './response.utils';
|
|
6
|
+
import { Env } from './env.utils';
|
|
7
|
+
import { getLogger } from './logger.utils';
|
|
8
|
+
/**
|
|
9
|
+
* Attaches a unique request ID to each request.
|
|
10
|
+
* Useful for request tracing and correlation between logs.
|
|
11
|
+
*
|
|
12
|
+
* @param {object} [options] - Configuration options
|
|
13
|
+
* @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
|
|
14
|
+
* @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
|
|
15
|
+
* @returns {Middleware} Express-compatible middleware
|
|
16
|
+
*/
|
|
17
|
+
export function requestId(options) {
|
|
18
|
+
var headerName = (options === null || options === void 0 ? void 0 : options.headerName) || 'X-Request-ID';
|
|
19
|
+
var exposeHeader = (options === null || options === void 0 ? void 0 : options.exposeHeader) !== false;
|
|
20
|
+
return function (req, res, next) {
|
|
21
|
+
// Use existing request ID from header or generate a new one
|
|
22
|
+
var existingId = req.headers[headerName.toLowerCase()];
|
|
23
|
+
var id = existingId || randomUUID();
|
|
24
|
+
// Attach ID to request object
|
|
25
|
+
req.id = id;
|
|
26
|
+
// Add ID to response headers
|
|
27
|
+
if (exposeHeader) {
|
|
28
|
+
res.setHeader(headerName, id);
|
|
29
|
+
}
|
|
30
|
+
next();
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Measures request processing time and logs or adds it to response headers.
|
|
35
|
+
*
|
|
36
|
+
* @param {object} [options] - Configuration options
|
|
37
|
+
* @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
|
|
38
|
+
* @param {boolean} [options.logOnComplete=false] - Whether to log timing info
|
|
39
|
+
* @returns {Middleware} Express-compatible middleware
|
|
40
|
+
*/
|
|
41
|
+
export function responseTime(options) {
|
|
42
|
+
var addHeader = (options === null || options === void 0 ? void 0 : options.addHeader) !== false;
|
|
43
|
+
var logOnComplete = (options === null || options === void 0 ? void 0 : options.logOnComplete) === true;
|
|
44
|
+
return function (req, res, next) {
|
|
45
|
+
var start = process.hrtime();
|
|
46
|
+
// Function to calculate elapsed time
|
|
47
|
+
var calculateDuration = function () {
|
|
48
|
+
var diff = process.hrtime(start);
|
|
49
|
+
return diff[0] * 1e3 + diff[1] * 1e-6; // Convert to ms
|
|
50
|
+
};
|
|
51
|
+
// Handle response completion
|
|
52
|
+
res.on('finish', function () {
|
|
53
|
+
var duration = calculateDuration();
|
|
54
|
+
if (addHeader) {
|
|
55
|
+
res.setHeader('X-Response-Time', "".concat(duration.toFixed(2), "ms"));
|
|
56
|
+
}
|
|
57
|
+
if (logOnComplete) {
|
|
58
|
+
var method = req.method, url = req.url;
|
|
59
|
+
getLogger().info("".concat(method, " ").concat(url, " - ").concat(duration.toFixed(2), "ms"));
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
next();
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Request timeout middleware.
|
|
67
|
+
* Aborts requests that take too long to process.
|
|
68
|
+
*
|
|
69
|
+
* @param {number} [timeoutMs=30000] - Timeout in milliseconds
|
|
70
|
+
* @returns {Middleware} Express-compatible middleware
|
|
71
|
+
*/
|
|
72
|
+
export function timeout(timeoutMs) {
|
|
73
|
+
if (timeoutMs === void 0) { timeoutMs = Config.Http.timeout; }
|
|
74
|
+
return function (req, res, next) {
|
|
75
|
+
// Set timeout for the request
|
|
76
|
+
var timer = setTimeout(function () {
|
|
77
|
+
res.status(408).json({
|
|
78
|
+
error: true,
|
|
79
|
+
message: 'Request timeout',
|
|
80
|
+
status: 408,
|
|
81
|
+
timestamp: new Date().toISOString()
|
|
82
|
+
});
|
|
83
|
+
}, timeoutMs);
|
|
84
|
+
// Clear timeout when response is sent
|
|
85
|
+
res.on('finish', function () {
|
|
86
|
+
clearTimeout(timer);
|
|
87
|
+
});
|
|
88
|
+
next();
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Creates a standardized error response object for API errors.
|
|
93
|
+
*
|
|
94
|
+
* @param {string} message - Error message
|
|
95
|
+
* @param {Request} req - Express request object
|
|
96
|
+
* @param {any} error - Original error object
|
|
97
|
+
* @param {object} [options] - Additional options
|
|
98
|
+
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
|
|
99
|
+
* @returns {object} Formatted error response
|
|
100
|
+
*/
|
|
101
|
+
var createErrorResponse = function (message, req, error, options) {
|
|
102
|
+
var isDev = Env.isDev();
|
|
103
|
+
var includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) && isDev;
|
|
104
|
+
var response = {
|
|
105
|
+
error: true,
|
|
106
|
+
message: message,
|
|
107
|
+
timestamp: new Date().toISOString(),
|
|
108
|
+
requestId: (error === null || error === void 0 ? void 0 : error.requestId) || req.id || uuid(),
|
|
109
|
+
path: req.originalUrl || req.url
|
|
110
|
+
};
|
|
111
|
+
// Include error code if present
|
|
112
|
+
if (error === null || error === void 0 ? void 0 : error.code) {
|
|
113
|
+
response.code = error.code;
|
|
114
|
+
}
|
|
115
|
+
// Include stack trace in development mode if requested
|
|
116
|
+
if (includeDetails && (error === null || error === void 0 ? void 0 : error.stack)) {
|
|
117
|
+
response.stack = error.stack.split('\n').map(function (line) { return line.trim(); });
|
|
118
|
+
}
|
|
119
|
+
return response;
|
|
120
|
+
};
|
|
121
|
+
/**
|
|
122
|
+
* Global error handling middleware with enhanced features.
|
|
123
|
+
*
|
|
124
|
+
* @param {object} [options] - Error handler options
|
|
125
|
+
* @param {boolean} [options.logErrors=true] - Whether to log errors
|
|
126
|
+
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
|
|
127
|
+
* @param {Function} [options.logger=getLogger().error] - Custom logging function
|
|
128
|
+
* @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware
|
|
129
|
+
*/
|
|
130
|
+
export function errorHandler(options) {
|
|
131
|
+
var logErrors = (options === null || options === void 0 ? void 0 : options.logErrors) !== false;
|
|
132
|
+
var includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) === true;
|
|
133
|
+
var logger = (options === null || options === void 0 ? void 0 : options.logger) || getLogger().error;
|
|
134
|
+
return function (err, req, res, _next) {
|
|
135
|
+
// Determine status code
|
|
136
|
+
var status = (err === null || err === void 0 ? void 0 : err.status) || (err === null || err === void 0 ? void 0 : err.statusCode) || HttpStatusCodes.INTERNAL_SERVER_ERROR;
|
|
137
|
+
// Log error if enabled
|
|
138
|
+
if (logErrors) {
|
|
139
|
+
var logMessage = "[ERROR] ".concat(req.method, " ").concat(req.originalUrl || req.url, ": ").concat(err.message || 'Unknown error');
|
|
140
|
+
logger(logMessage, err);
|
|
141
|
+
}
|
|
142
|
+
// Handle ErrorResponse instances (our custom error class)
|
|
143
|
+
if (err instanceof ErrorResponse) {
|
|
144
|
+
return res.status(status).json({
|
|
145
|
+
error: err.error,
|
|
146
|
+
message: err.message,
|
|
147
|
+
timestamp: err.timestamp,
|
|
148
|
+
requestId: err.requestId || req.id || uuid(),
|
|
149
|
+
path: req.originalUrl || req.url
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
// Handle any other errors
|
|
153
|
+
return res.status(status).json(createErrorResponse((err === null || err === void 0 ? void 0 : err.message) || 'Internal Server Error', req, err, {
|
|
154
|
+
includeDetails: includeDetails
|
|
155
|
+
}));
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
//# sourceMappingURL=middleware.utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO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GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAC5B,mBAAmB,CAAC,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,KAAI,uBAAuB,EAAE,GAAG,EAAE,GAAG,EAAE;YACrE,cAAc,gBAAA;SACf,CAAC,CACH,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { randomUUID } from 'crypto';\nimport { Config } from '../config';\nimport { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { ErrorResponse } from './response.utils';\nimport { Env } from './env.utils';\nimport { getLogger } from './logger.utils';\n\n/**\n * Type definitions for Express-compatible middleware\n */\ntype Request = {\n headers: Record<string, string | string[] | undefined>;\n method: string;\n url: string;\n ip?: string;\n body?: any;\n query?: Record<string, any>;\n params?: Record<string, any>;\n [key: string]: any;\n};\n\ntype Response = {\n status: (code: number) => Response;\n json: (data: any) => void;\n send: (data: any) => void;\n setHeader: (name: string, value: string | string[]) => void;\n end: (data?: any) => void;\n on: (event: string, callback: (...args: any[]) => void) => void;\n [key: string]: any;\n};\n\ntype NextFunction = (err?: Error | any) => void;\n\ntype Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: { headerName?: string; exposeHeader?: boolean }): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || randomUUID();\n\n // Attach ID to request object\n req.id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: { addHeader?: boolean; logOnComplete?: boolean }): Middleware {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req, res, next) => {\n const start = process.hrtime();\n\n // Function to calculate elapsed time\n const calculateDuration = (): number => {\n const diff = process.hrtime(start);\n return diff[0] * 1e3 + diff[1] * 1e-6; // Convert to ms\n };\n\n // Handle response completion\n res.on('finish', () => {\n const duration = calculateDuration();\n\n if (addHeader) {\n res.setHeader('X-Response-Time', `${duration.toFixed(2)}ms`);\n }\n\n if (logOnComplete) {\n const { method, url } = req;\n getLogger().info(`${method} ${url} - ${duration.toFixed(2)}ms`);\n }\n });\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = Config.Http.timeout): Middleware {\n return (req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n res.status(408).json({\n error: true,\n message: 'Request timeout',\n status: 408,\n timestamp: new Date().toISOString()\n });\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on('finish', () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates a standardized error response object for API errors.\n *\n * @param {string} message - Error message\n * @param {Request} req - Express request object\n * @param {any} error - Original error object\n * @param {object} [options] - Additional options\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @returns {object} Formatted error response\n */\nconst createErrorResponse = (message: string, req: Request, error: any, options?: { includeDetails?: boolean }) => {\n const isDev = Env.isDev();\n const includeDetails = options?.includeDetails && isDev;\n\n const response: Record<string, any> = {\n error: true,\n message,\n timestamp: new Date().toISOString(),\n requestId: error?.requestId || req.id || uuid(),\n path: req.originalUrl || req.url\n };\n\n // Include error code if present\n if (error?.code) {\n response.code = error.code;\n }\n\n // Include stack trace in development mode if requested\n if (includeDetails && error?.stack) {\n response.stack = error.stack.split('\\n').map((line: string) => line.trim());\n }\n\n return response;\n};\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {object} [options] - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @param {Function} [options.logger=getLogger().error] - Custom logging function\n * @returns {(err: any, req: Request, res: Response, next: NextFunction) => void} Error middleware\n */\nexport function errorHandler(options?: {\n logErrors?: boolean;\n includeDetails?: boolean;\n logger?: (message: string, error: any) => void;\n}) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n const logger = options?.logger || getLogger().error;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n const logMessage = `[ERROR] ${req.method} ${req.originalUrl || req.url}: ${err.message || 'Unknown error'}`;\n logger(logMessage, err);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n return res.status(status).json({\n error: err.error,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err.requestId || req.id || uuid(),\n path: req.originalUrl || req.url\n });\n }\n\n // Handle any other errors\n return res.status(status).json(\n createErrorResponse(err?.message || 'Internal Server Error', req, err, {\n includeDetails\n })\n );\n };\n}\n"]}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* @param {Record<any, any>} obj - The object to check.
|
|
5
5
|
* @returns {boolean} True if the object is empty, false otherwise.
|
|
6
6
|
*/
|
|
7
|
-
export declare
|
|
7
|
+
export declare function isObjEmpty(obj: Record<any, any>): boolean;
|
|
8
8
|
/**
|
|
9
9
|
* Returns a new object with only the specified keys picked.
|
|
10
10
|
*
|
|
@@ -14,7 +14,7 @@ export declare const isObjEmpty: (obj: Record<any, any>) => boolean;
|
|
|
14
14
|
* @param {K[]} keys - Keys to pick from the object.
|
|
15
15
|
* @returns {Pick<T, K>} New object with picked keys.
|
|
16
16
|
*/
|
|
17
|
-
export declare
|
|
17
|
+
export declare function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>;
|
|
18
18
|
/**
|
|
19
19
|
* Returns a new object with the specified keys omitted.
|
|
20
20
|
*
|
|
@@ -24,7 +24,7 @@ export declare const pick: <T extends object, K extends keyof T>(obj: T, keys: K
|
|
|
24
24
|
* @param {K[]} keys - Keys to omit from the object.
|
|
25
25
|
* @returns {Omit<T, K>} New object without omitted keys.
|
|
26
26
|
*/
|
|
27
|
-
export declare
|
|
27
|
+
export declare function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>;
|
|
28
28
|
/**
|
|
29
29
|
* Deeply merges two objects (mutates and returns the target object, not pure).
|
|
30
30
|
*
|
|
@@ -52,4 +52,66 @@ export declare function flattenObject<T extends Record<string, any>>(obj: T, pre
|
|
|
52
52
|
* @returns {any} The value at the given path, or undefined if not found.
|
|
53
53
|
*/
|
|
54
54
|
export declare function getValueByPath<T extends object>(obj: T, path: string): any;
|
|
55
|
+
/**
|
|
56
|
+
* Sets a value at a deeply nested key in an object using dot/bracket notation path.
|
|
57
|
+
* Creates intermediate objects and arrays as needed.
|
|
58
|
+
*
|
|
59
|
+
* @template T
|
|
60
|
+
* @param {T} obj - The object to modify.
|
|
61
|
+
* @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').
|
|
62
|
+
* @param {any} value - The value to set at the path.
|
|
63
|
+
* @returns {T} The modified object.
|
|
64
|
+
*/
|
|
65
|
+
export declare function setValueByPath<T extends object>(obj: T, path: string, value: any): T;
|
|
66
|
+
/**
|
|
67
|
+
* Performs a deep equality check between two objects.
|
|
68
|
+
*
|
|
69
|
+
* @param {any} a - First value to compare.
|
|
70
|
+
* @param {any} b - Second value to compare.
|
|
71
|
+
* @returns {boolean} True if values are deeply equal.
|
|
72
|
+
*/
|
|
73
|
+
export declare function isEqual(a: any, b: any): boolean;
|
|
74
|
+
/**
|
|
75
|
+
* Filters object properties based on a predicate function.
|
|
76
|
+
*
|
|
77
|
+
* @template T
|
|
78
|
+
* @param {T} obj - The source object.
|
|
79
|
+
* @param {(value: any, key: string, obj: T) => boolean} predicate - Filter function.
|
|
80
|
+
* @returns {Partial<T>} New object with filtered properties.
|
|
81
|
+
*/
|
|
82
|
+
export declare function filterObject<T extends object>(obj: T, predicate: (value: any, key: string, obj: T) => boolean): Partial<T>;
|
|
83
|
+
/**
|
|
84
|
+
* Maps object values to new values using a mapping function.
|
|
85
|
+
*
|
|
86
|
+
* @template T
|
|
87
|
+
* @template U
|
|
88
|
+
* @param {T} obj - The source object.
|
|
89
|
+
* @param {(value: any, key: string, obj: T) => U} mapFn - Mapping function.
|
|
90
|
+
* @returns {Record<keyof T, U>} New object with mapped values.
|
|
91
|
+
*/
|
|
92
|
+
export declare function mapObject<T extends object, U>(obj: T, mapFn: (value: any, key: string, obj: T) => U): Record<keyof T, U>;
|
|
93
|
+
/**
|
|
94
|
+
* Recursively freezes an object and all its properties.
|
|
95
|
+
* Makes an object immutable.
|
|
96
|
+
*
|
|
97
|
+
* @template T
|
|
98
|
+
* @param {T} obj - The object to freeze.
|
|
99
|
+
* @returns {Readonly<T>} The frozen object.
|
|
100
|
+
*/
|
|
101
|
+
export declare function deepFreeze<T extends object>(obj: T): Readonly<T>;
|
|
102
|
+
/**
|
|
103
|
+
* Safely checks if a value is an object (not null, not array).
|
|
104
|
+
*
|
|
105
|
+
* @param {unknown} value - Value to check.
|
|
106
|
+
* @returns {boolean} True if value is a non-null, non-array object.
|
|
107
|
+
*/
|
|
108
|
+
export declare function isObject(value: unknown): value is Record<string, any>;
|
|
109
|
+
/**
|
|
110
|
+
* Gets all paths in an object using dot notation.
|
|
111
|
+
*
|
|
112
|
+
* @param {Record<string, any>} obj - Object to analyze.
|
|
113
|
+
* @param {string} [parentPath=""] - Internal param for recursion.
|
|
114
|
+
* @returns {string[]} Array of all paths in dot notation.
|
|
115
|
+
*/
|
|
116
|
+
export declare function getAllPaths(obj: Record<string, any>, parentPath?: string): string[];
|
|
55
117
|
//# sourceMappingURL=obj.utils.d.ts.map
|