@catbee/utils 0.0.4 → 0.0.5
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 +693 -242
- package/build/esm/config.d.ts +20 -5
- package/build/esm/config.js +26 -6
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +2 -0
- package/build/esm/index.js +2 -0
- package/build/esm/index.js.map +1 -1
- package/build/esm/utils/cache.utils.js +16 -16
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +1 -1
- package/build/esm/utils/context-store.utils.js +1 -1
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.js +3 -2
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +291 -0
- package/build/esm/utils/decorators.utils.js +372 -40
- package/build/esm/utils/decorators.utils.js.map +1 -1
- package/build/esm/utils/env.utils.d.ts +186 -23
- package/build/esm/utils/env.utils.js +494 -91
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +107 -0
- package/build/esm/utils/logger.utils.js +207 -14
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +27 -7
- package/build/esm/utils/middleware.utils.js +25 -9
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esm/utils/request.utils.d.ts +77 -0
- package/build/esm/utils/request.utils.js +173 -0
- package/build/esm/utils/request.utils.js.map +1 -0
- package/build/esm/utils/response.utils.js +4 -4
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esnext/config.d.ts +20 -5
- package/build/esnext/config.js +26 -6
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +2 -0
- package/build/esnext/index.js +2 -0
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/utils/cache.utils.js +16 -16
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +1 -1
- package/build/esnext/utils/context-store.utils.js +1 -1
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.js +3 -2
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +291 -0
- package/build/esnext/utils/decorators.utils.js +348 -21
- package/build/esnext/utils/decorators.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.d.ts +186 -23
- package/build/esnext/utils/env.utils.js +445 -77
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +107 -0
- package/build/esnext/utils/logger.utils.js +178 -14
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +27 -7
- package/build/esnext/utils/middleware.utils.js +25 -9
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/esnext/utils/request.utils.d.ts +77 -0
- package/build/esnext/utils/request.utils.js +145 -0
- package/build/esnext/utils/request.utils.js.map +1 -0
- package/build/esnext/utils/response.utils.js +4 -4
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/src/config.d.ts +20 -5
- package/build/src/config.js +29 -7
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +2 -0
- package/build/src/index.js +5 -0
- package/build/src/index.js.map +1 -1
- package/build/src/utils/cache.utils.js +15 -15
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +1 -1
- package/build/src/utils/context-store.utils.js +1 -1
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.js +2 -1
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +291 -0
- package/build/src/utils/decorators.utils.js +350 -21
- package/build/src/utils/decorators.utils.js.map +1 -1
- package/build/src/utils/env.utils.d.ts +186 -23
- package/build/src/utils/env.utils.js +444 -76
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +107 -0
- package/build/src/utils/logger.utils.js +184 -14
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +27 -7
- package/build/src/utils/middleware.utils.js +24 -8
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/build/src/utils/request.utils.d.ts +77 -0
- package/build/src/utils/request.utils.js +152 -0
- package/build/src/utils/request.utils.js.map +1 -0
- package/build/src/utils/response.utils.js +4 -4
- package/build/src/utils/response.utils.js.map +1 -1
- package/package.json +12 -7
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications (including Express-based services). All utilities are tree-shakable and can be imported independently.
|
|
6
6
|
|
|
7
|
-
[build](https://
|
|
7
|
+
      
|
|
8
8
|
|
|
9
9
|
## 📦 Installation
|
|
10
10
|
|
|
@@ -50,58 +50,129 @@ console.log(isEmail("user@example.com")); // true
|
|
|
50
50
|
- [**Logger Utilities**](#-logger-utilities)
|
|
51
51
|
- [**Middleware Utilities**](#-middleware-utilities)
|
|
52
52
|
- [**Object Utilities**](#-object-utilities)
|
|
53
|
+
- [**Request Utilities**](#-request-utilities)
|
|
53
54
|
- [**Response Utilities**](#-response-utilities)
|
|
54
55
|
- [**String Utilities**](#-string-utilities)
|
|
55
56
|
- [**URL Utilities**](#-url-utilities)
|
|
56
57
|
- [**Validate Utilities**](#-validate-utilities)
|
|
57
|
-
- [**Decorators Utilities**](
|
|
58
|
+
- [**Decorators Utilities**](#-decorators-utilities)
|
|
58
59
|
|
|
59
60
|
---
|
|
60
61
|
|
|
61
62
|
## 📦 Array Utilities
|
|
62
63
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
- `
|
|
66
|
-
- `
|
|
67
|
-
- `
|
|
68
|
-
- `
|
|
69
|
-
- `
|
|
70
|
-
- `
|
|
71
|
-
- `
|
|
72
|
-
- `
|
|
73
|
-
- `
|
|
74
|
-
- `
|
|
75
|
-
- `
|
|
76
|
-
- `
|
|
77
|
-
- `
|
|
78
|
-
- `
|
|
79
|
-
- `
|
|
80
|
-
- `
|
|
64
|
+
A collection of functions for handling arrays with type-safety and efficiency.
|
|
65
|
+
|
|
66
|
+
- `chunk<T>(array: T[], size: number): T[][]` – Split array into chunks of specified size.
|
|
67
|
+
- `unique<T>(array: T[], keyFn?: (item: T) => unknown): T[]` – Remove duplicate items from an array, optionally by key.
|
|
68
|
+
- `flattenDeep<T>(array: any[]): T[]` – Deeply flatten a nested array.
|
|
69
|
+
- `random<T>(array: T[]): T | undefined` – Get a random element from an array.
|
|
70
|
+
- `groupBy<T>(array: T[], keyOrFn: keyof T | ((item: T) => string | number | symbol)): Record<string | number | symbol, T[]>` – Group array items by a key or function.
|
|
71
|
+
- `shuffle<T>(array: T[]): T[]` – Shuffle array elements randomly.
|
|
72
|
+
- `pluck<T, K extends keyof T>(array: T[], key: K): T[K][]` – Extract values for a given key from an array of objects.
|
|
73
|
+
- `difference<T>(a: T[], b: T[]): T[]` – Get elements in array `a` not present in array `b`.
|
|
74
|
+
- `intersect<T>(a: T[], b: T[]): T[]` – Get elements common to both arrays.
|
|
75
|
+
- `mergeSort<T>(array: T[], key: string | ((item: T) => any), direction?: "asc" | "desc"): T[]` – Sort array by key or function using merge sort.
|
|
76
|
+
- `zip<T>(...arrays: T[][]): T[][]` – Combine multiple arrays element-wise.
|
|
77
|
+
- `partition<T>(array: T[], predicate: (item: T, index: number, array: T[]) => boolean): [T[], T[]]` – Split array into two based on predicate.
|
|
78
|
+
- `range(start: number, end: number, step?: number): number[]` – Create an array of numbers in a range.
|
|
79
|
+
- `take<T>(array: T[], n?: number): T[]` – Take the first `n` elements from an array.
|
|
80
|
+
- `takeWhile<T>(array: T[], predicate: (item: T, index: number) => boolean): T[]` – Take elements from array while predicate is true.
|
|
81
|
+
- `compact<T>(array: T[]): NonNullable<T>[]` – Remove falsy values from an array.
|
|
82
|
+
- `countBy<T>(array: T[], keyFn: (item: T) => string | number | symbol): Record<string, number>` – Count occurrences by key or function.
|
|
83
|
+
|
|
84
|
+
**Examples:**
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
// Group users by their role
|
|
88
|
+
const users = [
|
|
89
|
+
{ id: 1, role: 'admin', name: 'Alice' },
|
|
90
|
+
{ id: 2, role: 'user', name: 'Bob' },
|
|
91
|
+
{ id: 3, role: 'user', name: 'Charlie' }
|
|
92
|
+
];
|
|
93
|
+
const groupedByRole = groupBy(users, 'role');
|
|
94
|
+
// { admin: [{ id: 1, ... }], user: [{ id: 2, ... }, { id: 3, ... }] }
|
|
95
|
+
|
|
96
|
+
// Partition an array into two groups
|
|
97
|
+
const numbers = [1, 2, 3, 4, 5, 6];
|
|
98
|
+
const [evens, odds] = partition(numbers, n => n % 2 === 0);
|
|
99
|
+
// evens: [2, 4, 6], odds: [1, 3, 5]
|
|
100
|
+
|
|
101
|
+
// Complex sorting with mergeSort
|
|
102
|
+
const items = [
|
|
103
|
+
{ nested: { value: 5 } },
|
|
104
|
+
{ nested: { value: 2 } },
|
|
105
|
+
{ nested: { value: 8 } }
|
|
106
|
+
];
|
|
107
|
+
const sorted = mergeSort(items, (item) => item.nested.value);
|
|
108
|
+
// [{ nested: { value: 2 } }, { nested: { value: 5 } }, { nested: { value: 8 } }]
|
|
109
|
+
```
|
|
81
110
|
|
|
82
111
|
## ⏳ Async Utilities
|
|
83
112
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
- `
|
|
87
|
-
- `
|
|
88
|
-
- `
|
|
89
|
-
- `
|
|
90
|
-
- `
|
|
91
|
-
- `
|
|
92
|
-
- `
|
|
93
|
-
- `
|
|
94
|
-
- `
|
|
95
|
-
- `
|
|
96
|
-
- `
|
|
97
|
-
- `
|
|
98
|
-
- `
|
|
113
|
+
Functions for handling asynchronous operations with better control flow and error handling.
|
|
114
|
+
|
|
115
|
+
- `sleep(ms: number): Promise<void>` – Pause execution for a given number of milliseconds.
|
|
116
|
+
- `debounce<T>(fn: T, delay: number): T & { cancel(): void; flush(): void }` – Debounce function calls, only invoking after delay.
|
|
117
|
+
- `throttle<T>(fn: T, limit: number, opts?): (...args: Parameters<T>) => void` – Throttle function calls to a maximum rate.
|
|
118
|
+
- `retry<T>(fn: () => Promise<T>, retries?: number, delay?: number, backoff?: boolean, onRetry?): Promise<T>` – Retry a promise-returning function with optional backoff.
|
|
119
|
+
- `withTimeout<T>(promise: Promise<T>, ms: number, message?: string): Promise<T>` – Reject promise if it takes longer than specified time.
|
|
120
|
+
- `runInBatches<T>(tasks: (() => Promise<T>)[], limit: number): Promise<T[]>` – Run async tasks in batches with concurrency limit.
|
|
121
|
+
- `singletonAsync<TArgs extends unknown[], TResult>(fn: (...args: TArgs) => Promise<TResult>, drop?: boolean): (...args: TArgs) => Promise<TResult>` – Ensure only one instance of an async function runs at a time.
|
|
122
|
+
- `settleAll<T>(tasks: (() => Promise<T>)[]): Promise<PromiseSettledResult<T>[]>` – Run all tasks and return their settled results.
|
|
123
|
+
- `createTaskQueue(limit: number): TaskQueue` – Create a queue to run tasks with concurrency control.
|
|
124
|
+
- `runInSeries<T>(tasks: (() => Promise<T>)[]): Promise<T[]>` – Run async tasks one after another.
|
|
125
|
+
- `memoizeAsync<T, Args extends any[]>(fn: (...args: Args) => Promise<T>, options?): (...args: Args) => Promise<T>` – Memoize async function results.
|
|
126
|
+
- `abortable<T>(promise: Promise<T>, signal: AbortSignal, abortValue?: any): Promise<T>` – Make a promise abortable via AbortSignal.
|
|
127
|
+
- `createDeferred<T>(): [Promise<T>, (value: T | PromiseLike<T>) => void, (reason?: any) => void]` – Create a deferred promise with resolve/reject.
|
|
128
|
+
- `waterfall<T>(fns: Array<(input: any) => Promise<any>>): (initialValue: any) => Promise<T>` – Run async functions in sequence, passing result to next.
|
|
129
|
+
- `rateLimit<T>(fn: (...args: any[]) => Promise<T>, maxCalls: number, interval: number): (...args: any[]) => Promise<T>` – Limit the rate of async function calls.
|
|
130
|
+
|
|
131
|
+
**Examples:**
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
// Retry a flaky API call
|
|
135
|
+
const fetchData = async () => {
|
|
136
|
+
const response = await fetch('https://api.example.com/data');
|
|
137
|
+
if (!response.ok) throw new Error(`HTTP error ${response.status}`);
|
|
138
|
+
return await response.json();
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const result = await retry(
|
|
142
|
+
fetchData,
|
|
143
|
+
3, // retry 3 times
|
|
144
|
+
1000, // wait 1 second between retries
|
|
145
|
+
true, // use exponential backoff
|
|
146
|
+
(err, attempt) => console.log(`Attempt ${attempt} failed: ${err.message}`)
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
// Process items in batches to avoid overloading resources
|
|
150
|
+
const processItem = async (id) => {
|
|
151
|
+
// Process a single item...
|
|
152
|
+
return `Processed ${id}`;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const itemIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
|
156
|
+
const tasks = itemIds.map(id => processItem(id));
|
|
157
|
+
const results = await runInBatches(tasks, 3); // Process 3 items concurrently
|
|
158
|
+
|
|
159
|
+
// Function waterfall (pipeline)
|
|
160
|
+
const pipeline = waterfall([
|
|
161
|
+
async (input) => input * 2,
|
|
162
|
+
async (input) => input + 10,
|
|
163
|
+
async (input) => `Result: ${input}`
|
|
164
|
+
]);
|
|
165
|
+
|
|
166
|
+
const finalResult = await pipeline(5); // "Result: 20"
|
|
167
|
+
```
|
|
99
168
|
|
|
100
169
|
## 🗃️ Cache Utilities
|
|
101
170
|
|
|
102
|
-
|
|
171
|
+
In-memory TTL cache with advanced features for efficient data caching and retrieval.
|
|
103
172
|
|
|
104
|
-
|
|
173
|
+
- `TTLCache<K, V>(options?: TTLCacheOptions)` – Create a time-to-live in-memory cache with various methods for managing entries.
|
|
174
|
+
|
|
175
|
+
**Examples:**
|
|
105
176
|
```ts
|
|
106
177
|
const cache = new TTLCache<string, number>({ ttlMs: 3600_000 });
|
|
107
178
|
cache.set("foo", 42);
|
|
@@ -112,28 +183,42 @@ cache.cleanup(); // cleans expired
|
|
|
112
183
|
|
|
113
184
|
## ⚙️ Config
|
|
114
185
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
- `
|
|
118
|
-
- `
|
|
119
|
-
- `
|
|
186
|
+
Global configuration settings for the application, including logging, HTTP, and cache settings.
|
|
187
|
+
|
|
188
|
+
- `config.logger.level` – Set the logging level (e.g., 'info', 'debug').
|
|
189
|
+
- `config.logger.name` – Set the logger name.
|
|
190
|
+
- `config.logger.pretty` – Enable pretty print for logs.
|
|
191
|
+
- `config.http.timeout` – Set HTTP request timeout in milliseconds.
|
|
192
|
+
- `config.cache.defaultTtl` – Set default cache TTL in seconds.
|
|
193
|
+
- `setConfig(value: Partial<typeof config>): void` – Update configuration settings.
|
|
194
|
+
- `getConfig(): typeof config` – Get the current configuration settings.
|
|
195
|
+
|
|
196
|
+
**Example:**
|
|
197
|
+
```ts
|
|
198
|
+
import { setConfig } from "@catbee/utils";
|
|
199
|
+
|
|
200
|
+
// Configure logging
|
|
201
|
+
setConfig({ logger: { pretty: true } });
|
|
202
|
+
|
|
203
|
+
console.log(getConfig());
|
|
204
|
+
```
|
|
120
205
|
|
|
121
206
|
## 🧩 Context Store
|
|
122
207
|
|
|
123
|
-
|
|
208
|
+
Per-request context management using AsyncLocalStorage, allowing for easy sharing of data across async calls.
|
|
124
209
|
|
|
125
|
-
|
|
126
|
-
- `getInstance(): AsyncLocalStorage<Store>`
|
|
210
|
+
- `ContextStore` – Per-request context using AsyncLocalStorage.
|
|
211
|
+
- `getInstance(): AsyncLocalStorage<Store>` – Get the AsyncLocalStorage instance.
|
|
127
212
|
- `getAll(): Store | undefined` – Get the current context store.
|
|
128
|
-
- `run(store: Store, callback: () => void): void`
|
|
129
|
-
- `set(key: symbol, value: unknown): void`
|
|
130
|
-
- `get<T>(key: symbol): T | undefined`
|
|
131
|
-
- `has(key: symbol): boolean`
|
|
132
|
-
- `delete(key: symbol): boolean`
|
|
133
|
-
- `patch(values: Partial<Record<symbol, unknown>>): void`
|
|
134
|
-
- `withValue(key: symbol, value: unknown, callback: () => T): T`
|
|
135
|
-
- `extend(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T`
|
|
136
|
-
- `createExpressMiddleware(initialValuesFactory?): Middleware`
|
|
213
|
+
- `run(store: Store, callback: () => void): void` – Run a callback with a specific store context.
|
|
214
|
+
- `set(key: symbol, value: unknown): void` – Set a value in the current store.
|
|
215
|
+
- `get<T>(key: symbol): T | undefined` – Get a value from the current store.
|
|
216
|
+
- `has(key: symbol): boolean` – Check if a key exists in the store.
|
|
217
|
+
- `delete(key: symbol): boolean` – Remove a key from the store.
|
|
218
|
+
- `patch(values: Partial<Record<symbol, unknown>>): void` – Update multiple values in the store.
|
|
219
|
+
- `withValue(key: symbol, value: unknown, callback: () => T): T` – Temporarily set a value for a callback.
|
|
220
|
+
- `extend(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T` – Temporarily extend the store for a callback.
|
|
221
|
+
- `createExpressMiddleware(initialValuesFactory?): Middleware` – Create Express middleware for context.
|
|
137
222
|
|
|
138
223
|
- `StoreKeys` – Common context keys.
|
|
139
224
|
- `getRequestId(): string | undefined` – Get the current request ID from context.
|
|
@@ -146,7 +231,7 @@ import crypto from "crypto";
|
|
|
146
231
|
export function setupRequestContext(req, res, next) {
|
|
147
232
|
const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
|
|
148
233
|
ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
|
|
149
|
-
const logger = getLogger().child({
|
|
234
|
+
const logger = getLogger().child({ requestId });
|
|
150
235
|
ContextStore.set(StoreKeys.LOGGER, logger);
|
|
151
236
|
logger.info("Request context initialized");
|
|
152
237
|
next();
|
|
@@ -157,111 +242,252 @@ app.use(setupRequestContext);
|
|
|
157
242
|
|
|
158
243
|
## 🔐 Crypto Utilities
|
|
159
244
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
- `
|
|
163
|
-
- `
|
|
164
|
-
- `
|
|
165
|
-
- `
|
|
166
|
-
- `
|
|
167
|
-
- `
|
|
168
|
-
- `
|
|
169
|
-
- `
|
|
170
|
-
- `
|
|
171
|
-
- `
|
|
172
|
-
- `
|
|
173
|
-
- `
|
|
174
|
-
- `
|
|
245
|
+
Secure cryptographic functions for encryption, hashing, and token generation.
|
|
246
|
+
|
|
247
|
+
- `hmac(algorithm: string, input: string, secret: string, encoding?: BinaryToTextEncoding): string` – Generate an HMAC hash.
|
|
248
|
+
- `hash(algorithm: string, input: string, encoding?: BinaryToTextEncoding): string` – Generate a hash using a specified algorithm.
|
|
249
|
+
- `sha256Hmac(input: string, secret: string): string` – Generate a SHA256 HMAC.
|
|
250
|
+
- `sha1(input: string, encoding?: BinaryToTextEncoding): string` – Generate a SHA1 hash.
|
|
251
|
+
- `sha256(input: string, encoding?: BinaryToTextEncoding): string` – Generate a SHA256 hash.
|
|
252
|
+
- `md5(input: string): string` – Generate an MD5 hash.
|
|
253
|
+
- `randomString(): string` – Generate a cryptographically secure random string.
|
|
254
|
+
- `generateRandomBytes(byteLength?: number): Buffer` – Generate random bytes.
|
|
255
|
+
- `generateRandomBytesAsString(byteLength?: number, encoding?: BinaryToTextEncoding): string` – Generate random bytes as a string.
|
|
256
|
+
- `generateApiKey(prefix?: string, byteLength?: number): string` – Generate an API key with optional prefix.
|
|
257
|
+
- `safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean` – Timing-safe string comparison.
|
|
258
|
+
- `encrypt(data: string | Buffer, key: string | Buffer, options?): Promise<EncryptionResult>` – Encrypt data using AES.
|
|
259
|
+
- `decrypt(encryptedData: EncryptionResult, key: string | Buffer, options?): Promise<string | Buffer>` – Decrypt AES encrypted data.
|
|
260
|
+
- `createSignedToken(payload: object, secret: string, expiresInSeconds?: number): string` – Create a signed token (JWT-like).
|
|
261
|
+
- `verifySignedToken(token: string, secret: string): object | null` – Verify and decode a signed token.
|
|
262
|
+
|
|
263
|
+
**Examples:**
|
|
264
|
+
|
|
265
|
+
```ts
|
|
266
|
+
// Generate and verify JWT-like tokens
|
|
267
|
+
const payload = { userId: 123, permissions: ['read', 'write'] };
|
|
268
|
+
const secret = 'secret-key';
|
|
269
|
+
|
|
270
|
+
const token = createSignedToken(payload, secret, 3600); // expires in 1 hour
|
|
271
|
+
|
|
272
|
+
// Later, verify and decode
|
|
273
|
+
const decodedPayload = verifySignedToken(token, secret);
|
|
274
|
+
if (decodedPayload) {
|
|
275
|
+
console.log(`User ID: ${decodedPayload.userId}`);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Generate API keys for your service
|
|
279
|
+
const apiKey = generateApiKey('usr_', 32);
|
|
280
|
+
// usr_8f7d8937a9f27cb6b3f8a0928f5c9c1e
|
|
281
|
+
```
|
|
175
282
|
|
|
176
283
|
## 📂 Directory Utilities
|
|
177
284
|
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
- `
|
|
181
|
-
- `
|
|
182
|
-
- `
|
|
183
|
-
- `
|
|
184
|
-
- `
|
|
185
|
-
- `
|
|
186
|
-
- `
|
|
187
|
-
- `
|
|
188
|
-
- `
|
|
189
|
-
- `
|
|
190
|
-
- `
|
|
191
|
-
- `
|
|
192
|
-
- `
|
|
193
|
-
- `
|
|
194
|
-
- `
|
|
195
|
-
- `
|
|
196
|
-
- `
|
|
285
|
+
File and directory manipulation utilities for managing file system interactions.
|
|
286
|
+
|
|
287
|
+
- `ensureDir(dirPath: string): Promise<void>` – Ensure a directory exists.
|
|
288
|
+
- `listFiles(dirPath: string, recursive?: boolean): Promise<string[]>` – List files in a directory.
|
|
289
|
+
- `deleteDirRecursive(dirPath: string): Promise<void>` – Delete a directory and its contents.
|
|
290
|
+
- `isDirectory(pathStr: string): Promise<boolean>` – Check if a path is a directory.
|
|
291
|
+
- `copyDir(src: string, dest: string): Promise<void>` – Copy a directory recursively.
|
|
292
|
+
- `moveDir(src: string, dest: string): Promise<void>` – Move a directory.
|
|
293
|
+
- `emptyDir(dirPath: string): Promise<void>` – Remove all contents from a directory.
|
|
294
|
+
- `getDirSize(dirPath: string): Promise<number>` – Get the total size of a directory.
|
|
295
|
+
- `watchDir(dirPath: string, callback): () => void` – Watch a directory for changes.
|
|
296
|
+
- `findFilesByPattern(pattern: string, options?): Promise<string[]>` – Find files matching a pattern.
|
|
297
|
+
- `getSubdirectories(dirPath: string, recursive?: boolean): Promise<string[]>` – Get subdirectories of a directory.
|
|
298
|
+
- `ensureEmptyDir(dirPath: string): Promise<void>` – Ensure a directory exists and is empty.
|
|
299
|
+
- `createTempDir(options?): Promise<{ path: string, cleanup: () => Promise<void> }>` – Create a temporary directory.
|
|
300
|
+
- `findNewestFile(dirPath: string, recursive?: boolean): Promise<string | null>` – Find the newest file in a directory.
|
|
301
|
+
- `findOldestFile(dirPath: string, recursive?: boolean): Promise<string | null>` – Find the oldest file in a directory.
|
|
302
|
+
- `findInDir(dirPath: string, predicate, recursive?: boolean): Promise<string[]>` – Find files in a directory by predicate.
|
|
303
|
+
- `watchDirRecursive(dirPath: string, callback, includeSubdirs?: boolean): Promise<() => void>` – Watch a directory and subdirectories for changes.
|
|
304
|
+
- `getDirStats(dirPath: string): Promise<{ fileCount: number, dirCount: number, totalSize: number }>` – Get statistics for a directory.
|
|
305
|
+
- `walkDir(dirPath: string, options): Promise<void>` – Walk a directory tree with callbacks.
|
|
306
|
+
|
|
307
|
+
**Examples:**
|
|
308
|
+
|
|
309
|
+
```ts
|
|
310
|
+
// Safely ensure a directory exists and is empty
|
|
311
|
+
await ensureEmptyDir('./temp/uploads');
|
|
312
|
+
|
|
313
|
+
// Find specific files in a directory structure
|
|
314
|
+
const imageFiles = await findInDir('./content',
|
|
315
|
+
(path) => path.endsWith('.jpg') || path.endsWith('.png'),
|
|
316
|
+
true // recursive search
|
|
317
|
+
);
|
|
318
|
+
|
|
319
|
+
// Create a temporary directory that cleans itself up
|
|
320
|
+
const { path, cleanup } = await createTempDir({
|
|
321
|
+
prefix: 'app-',
|
|
322
|
+
parentDir: './temp'
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
try {
|
|
326
|
+
// Use the temporary directory...
|
|
327
|
+
await writeTextFile(`${path}/data.txt`, 'Hello world');
|
|
328
|
+
} finally {
|
|
329
|
+
// Clean up when done
|
|
330
|
+
await cleanup();
|
|
331
|
+
}
|
|
332
|
+
```
|
|
197
333
|
|
|
198
334
|
## 🌱 Environment Utilities
|
|
199
335
|
|
|
200
|
-
|
|
336
|
+
Environment variable management with powerful type-safe access, validation, and transformation capabilities.
|
|
337
|
+
|
|
338
|
+
- `Environment` enum – (`DEVELOPMENT`, `PRODUCTION`, `STAGING`, `TESTING`) – Enum for environment types.
|
|
201
339
|
- `Env` class – Environment variable helpers.
|
|
340
|
+
- `isDev(): boolean` – Check if running in development environment.
|
|
341
|
+
- `isProd(): boolean` – Check if running in production environment.
|
|
342
|
+
- `isTest(): boolean` – Check if running in test environment.
|
|
343
|
+
- `isStaging(): boolean` – Check if running in staging environment.
|
|
344
|
+
- `set(key: string, value: string): void` – Set an environment variable.
|
|
345
|
+
- `getAll(): object` – Get all environment variables.
|
|
346
|
+
- `get(key: string, defaultValue: string): string` – Get a variable with a default value.
|
|
347
|
+
- `getRequired(key: string): string` – Get a required variable, throw if missing.
|
|
348
|
+
- `getOrFail(key: string): string` – Alias for getRequired.
|
|
349
|
+
- `getNumber(key: string, defaultValue: number): number` – Get a variable as a number.
|
|
350
|
+
- `getNumberRequired(key: string): number` – Get a required number variable.
|
|
351
|
+
- `getInteger(key: string, defaultValue: number, options?): number` – Get an integer with optional validation.
|
|
352
|
+
- `getBoolean(key: string, defaultValue?: boolean): boolean` – Get a variable as a boolean.
|
|
353
|
+
- `getBooleanRequired(key: string): boolean` – Get a required boolean variable.
|
|
354
|
+
- `getJSON<T>(key: string, defaultValue: T): T` – Parse a variable as JSON.
|
|
355
|
+
- `getArray<T = string>(key: string, defaultValue?: T[], splitter?: string, transform?): T[]` – Parse a variable as an array.
|
|
356
|
+
- `getNumberArray(key: string, defaultValue?: number[], splitter?: string): number[]` – Parse a variable as an array of numbers.
|
|
357
|
+
- `getEnum<T extends string>(key: string, allowedValues: T[], defaultValue: T): T` – Get a variable as an enum value.
|
|
358
|
+
- `getNumberEnum(key: string, allowedValues: number[], defaultValue: number): number` – Get a variable as a numeric enum.
|
|
359
|
+
- `getUrl(key: string, defaultValue: string, options?): string` – Get and validate a URL variable.
|
|
360
|
+
- `getEmail(key: string, defaultValue: string): string` – Get and validate an email variable.
|
|
361
|
+
- `getPath(key: string, defaultValue: string, options?): string` – Get and validate a file path variable.
|
|
362
|
+
- `getPort(key: string, defaultValue: number): number` – Get and validate a port number.
|
|
363
|
+
- `getDate(key: string, defaultValue?: string | Date): Date` – Parse a variable as a date.
|
|
364
|
+
- `getDuration(key: string, defaultValue?: string | number): number` – Parse a variable as a duration in ms.
|
|
365
|
+
- `getSafeEnv(sensitiveKeys?: string[]): Record<string, string>` – Get environment with sensitive values masked.
|
|
366
|
+
- `getWithDefault(key: string, defaultFn: () => string): string` – Get a variable or compute a default.
|
|
367
|
+
- `loadFromFile(path: string): Record<string, string>` – Load variables from a .env file.
|
|
368
|
+
- `has(key: string): boolean` – Check if a variable exists.
|
|
369
|
+
- `delete(key: string): void` – Delete a variable.
|
|
370
|
+
- `clearCache(): void` – Clear the internal cache.
|
|
371
|
+
|
|
372
|
+
**Examples:**
|
|
373
|
+
|
|
374
|
+
```ts
|
|
375
|
+
import { Env, Environment } from "@catbee/utils";
|
|
202
376
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
377
|
+
// Check current environment
|
|
378
|
+
if (Env.isDev()) {
|
|
379
|
+
console.log("Running in development mode");
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// Variable expansion (reference other environment variables)
|
|
383
|
+
// If DATABASE_HOST=localhost and DATABASE_NAME=myapp
|
|
384
|
+
Env.set('DATABASE_URL', 'postgres://${DATABASE_HOST}:5432/${DATABASE_NAME}');
|
|
385
|
+
const dbUrl = Env.get('DATABASE_URL', ''); // "postgres://localhost:5432/myapp"
|
|
386
|
+
|
|
387
|
+
// Load from .env file
|
|
388
|
+
Env.loadFromFile('.env.local');
|
|
389
|
+
|
|
390
|
+
// Number validation with range checks
|
|
391
|
+
const port = Env.getInteger('PORT', 3000, { min: 1024, max: 49151 });
|
|
392
|
+
const workerCount = Env.getNumber('WORKER_COUNT', 4);
|
|
393
|
+
|
|
394
|
+
// URL validation with protocol restrictions
|
|
395
|
+
const apiUrl = Env.getUrl('API_URL', 'https://api.example.com', {
|
|
396
|
+
protocols: ['https'],
|
|
397
|
+
requireTld: true,
|
|
398
|
+
allowLocalhost: Env.isDev() // allow localhost in development
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
// Path validation with existence check
|
|
402
|
+
const configPath = Env.getPath('CONFIG_PATH', './config.json', {
|
|
403
|
+
mustExist: true,
|
|
404
|
+
allowedExtensions: ['.json', '.yaml']
|
|
405
|
+
});
|
|
406
|
+
|
|
407
|
+
// Parse arrays with automatic transformation
|
|
408
|
+
const ports = Env.getNumberArray('ALLOWED_PORTS', [80, 443]);
|
|
409
|
+
const features = Env.getArray('ENABLED_FEATURES', [], ',');
|
|
410
|
+
|
|
411
|
+
// Parse dates and durations
|
|
412
|
+
const launchDate = Env.getDate('LAUNCH_DATE');
|
|
413
|
+
const cacheTtl = Env.getDuration('CACHE_TTL', '1h'); // in milliseconds
|
|
414
|
+
|
|
415
|
+
// Complex configurations from JSON
|
|
416
|
+
const serverConfig = Env.getJSON('SERVER_CONFIG', {
|
|
417
|
+
maxConnections: 100,
|
|
418
|
+
timeout: 30000,
|
|
419
|
+
retries: 3
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
// Safe environment printing (hiding secrets)
|
|
423
|
+
console.log(Env.getSafeEnv(['PASSWORD', 'API_KEY', 'SECRET']));
|
|
424
|
+
|
|
425
|
+
// Lazy default evaluation (only runs if variable is missing)
|
|
426
|
+
const hostname = Env.getWithDefault('HOSTNAME', () => {
|
|
427
|
+
console.log('Computing hostname...');
|
|
428
|
+
return require('os').hostname();
|
|
429
|
+
});
|
|
430
|
+
```
|
|
228
431
|
|
|
229
432
|
## 🚨 Exception Utilities
|
|
230
433
|
|
|
231
|
-
- `HttpError
|
|
232
|
-
- `
|
|
233
|
-
- `
|
|
234
|
-
- `
|
|
235
|
-
- `
|
|
236
|
-
- `
|
|
434
|
+
- `HttpError` – Base HTTP error class.
|
|
435
|
+
- `InternalServerErrorException` – HTTP 500 error.
|
|
436
|
+
- `UnauthorizedException` – HTTP 401 error.
|
|
437
|
+
- `BadRequestException` – HTTP 400 error.
|
|
438
|
+
- `NotFoundException` – HTTP 404 error.
|
|
439
|
+
- `ForbiddenException` – HTTP 403 error.
|
|
440
|
+
- `ConflictException` – HTTP 409 error.
|
|
441
|
+
- `BadGatewayException` – HTTP 502 error.
|
|
442
|
+
- `TooManyRequestsException` – HTTP 429 error.
|
|
443
|
+
- `ServiceUnavailableException` – HTTP 503 error.
|
|
444
|
+
- `GatewayTimeoutException` – HTTP 504 error.
|
|
445
|
+
- `UnprocessableEntityException` – HTTP 422 error.
|
|
446
|
+
- `MethodNotAllowedException` – HTTP 405 error.
|
|
447
|
+
- `NotAcceptableException` – HTTP 406 error.
|
|
448
|
+
- `RequestTimeoutException` – HTTP 408 error.
|
|
449
|
+
- `UnsupportedMediaTypeException` – HTTP 415 error.
|
|
450
|
+
- `PayloadTooLargeException` – HTTP 413 error.
|
|
451
|
+
- `InsufficientStorageException` – HTTP 507 error.
|
|
452
|
+
- `isHttpError(error: unknown): error is ErrorResponse` – Check if an error is an HTTP error.
|
|
453
|
+
- `createHttpError(status: number, message?: string): ErrorResponse` – Create a custom HTTP error.
|
|
454
|
+
- `hasErrorShape(error: unknown): error is { message: string; status?: number; code?: string }` – Check if an error has a standard shape.
|
|
455
|
+
- `getErrorMessage(error: unknown): string` – Extract a message from any error.
|
|
456
|
+
- `withErrorHandling<T extends (...args: any[]) => Promise<any>>(handler: T): (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>` – Wrap an async function with error handling.
|
|
237
457
|
|
|
238
458
|
## 📁 File System Utilities
|
|
239
459
|
|
|
240
|
-
- `fileExists(path: string): Promise<boolean>`
|
|
241
|
-
- `readJsonFile<T>(path: string): Promise<T | null>`
|
|
242
|
-
- `writeJsonFile(path: string, data: any, space?: number): Promise<void>`
|
|
243
|
-
- `deleteFileIfExists(path: string): Promise<boolean>`
|
|
244
|
-
- `readTextFile(path: string, encoding?: BufferEncoding): Promise<string | null>`
|
|
245
|
-
- `writeTextFile(path: string, content: string, encoding?: BufferEncoding): Promise<boolean>`
|
|
246
|
-
- `appendTextFile(path: string, content: string, encoding?: BufferEncoding): Promise<boolean>`
|
|
247
|
-
- `copyFile(source: string, destination: string, overwrite?: boolean): Promise<boolean>`
|
|
248
|
-
- `moveFile(oldPath: string, newPath: string): Promise<boolean>`
|
|
249
|
-
- `getFileStats(path: string): Promise<fs.Stats | null>`
|
|
250
|
-
- `createTempFile(options?): Promise<string>`
|
|
251
|
-
- `streamFile(source: string, destination: string): Promise<void>`
|
|
252
|
-
- `readDirectory(dirPath: string, options?): Promise<string[]>`
|
|
253
|
-
- `createDirectory(dirPath: string, recursive?: boolean): Promise<boolean>`
|
|
254
|
-
- `safeReadJsonFile<T>(path: string): Promise<{ data: T | null; error: Error | null }>`
|
|
255
|
-
- `isFile(path: string): Promise<boolean>`
|
|
256
|
-
- `getFileSize(path: string): Promise<number>`
|
|
257
|
-
- `readFileBuffer(path: string): Promise<Buffer | null>`
|
|
460
|
+
- `fileExists(path: string): Promise<boolean>` – Check if a file exists.
|
|
461
|
+
- `readJsonFile<T>(path: string): Promise<T | null>` – Read and parse a JSON file.
|
|
462
|
+
- `writeJsonFile(path: string, data: any, space?: number): Promise<void>` – Write data to a JSON file.
|
|
463
|
+
- `deleteFileIfExists(path: string): Promise<boolean>` – Delete a file if it exists.
|
|
464
|
+
- `readTextFile(path: string, encoding?: BufferEncoding): Promise<string | null>` – Read a text file.
|
|
465
|
+
- `writeTextFile(path: string, content: string, encoding?: BufferEncoding): Promise<boolean>` – Write text to a file.
|
|
466
|
+
- `appendTextFile(path: string, content: string, encoding?: BufferEncoding): Promise<boolean>` – Append text to a file.
|
|
467
|
+
- `copyFile(source: string, destination: string, overwrite?: boolean): Promise<boolean>` – Copy a file.
|
|
468
|
+
- `moveFile(oldPath: string, newPath: string): Promise<boolean>` – Move or rename a file.
|
|
469
|
+
- `getFileStats(path: string): Promise<fs.Stats | null>` – Get file statistics.
|
|
470
|
+
- `createTempFile(options?): Promise<string>` – Create a temporary file.
|
|
471
|
+
- `streamFile(source: string, destination: string): Promise<void>` – Stream file contents.
|
|
472
|
+
- `readDirectory(dirPath: string, options?): Promise<string[]>` – Read directory contents.
|
|
473
|
+
- `createDirectory(dirPath: string, recursive?: boolean): Promise<boolean>` – Create a directory.
|
|
474
|
+
- `safeReadJsonFile<T>(path: string): Promise<{ data: T | null; error: Error | null }>` – Safely read a JSON file.
|
|
475
|
+
- `isFile(path: string): Promise<boolean>` – Check if a path is a file.
|
|
476
|
+
- `getFileSize(path: string): Promise<number>` – Get the size of a file.
|
|
477
|
+
- `readFileBuffer(path: string): Promise<Buffer | null>` – Read a file as a buffer.
|
|
478
|
+
|
|
479
|
+
**Examples:**
|
|
480
|
+
```ts
|
|
481
|
+
import { readFileBuffer } from "@catbee/utils";
|
|
482
|
+
const buffer = await readFileBuffer("./file.txt");
|
|
483
|
+
```
|
|
258
484
|
|
|
259
485
|
## 📊 HTTP Status Codes
|
|
260
486
|
|
|
261
487
|
A typed enum with all HTTP status codes and their standard messages.
|
|
262
488
|
|
|
263
|
-
- `HttpStatusCodes.OK === 200`
|
|
264
|
-
- `HttpStatusCodes.NOT_FOUND === 404`
|
|
489
|
+
- `HttpStatusCodes.OK === 200` – HTTP 200 OK.
|
|
490
|
+
- `HttpStatusCodes.NOT_FOUND === 404` – HTTP 404 Not Found.
|
|
265
491
|
- ...and so on.
|
|
266
492
|
|
|
267
493
|
**Example:**
|
|
@@ -272,103 +498,325 @@ res.status(HttpStatusCodes.BAD_REQUEST).send("Invalid payload");
|
|
|
272
498
|
|
|
273
499
|
## 🆔 ID Utilities
|
|
274
500
|
|
|
275
|
-
- `uuid(): string`
|
|
276
|
-
- `nanoId(size?: number): string`
|
|
277
|
-
- `randomHex(byteLength?: number): string`
|
|
278
|
-
- `randomInt(min: number, max: number): number`
|
|
279
|
-
- `randomBase64(byteLength?: number): number`
|
|
501
|
+
- `uuid(): string` – Generate a UUID v4.
|
|
502
|
+
- `nanoId(size?: number): string` – Generate a compact, URL-friendly unique ID.
|
|
503
|
+
- `randomHex(byteLength?: number): string` – Generate a random hexadecimal string.
|
|
504
|
+
- `randomInt(min: number, max: number): number` – Generate a random integer in a range.
|
|
505
|
+
- `randomBase64(byteLength?: number): number` – Generate a random Base64 string.
|
|
506
|
+
|
|
507
|
+
**Examples:**
|
|
508
|
+
```ts
|
|
509
|
+
import { nanoId } from "@catbee/utils";
|
|
510
|
+
const id = nanoId();
|
|
511
|
+
```
|
|
280
512
|
|
|
281
513
|
## 📄 Logger Utilities
|
|
282
514
|
|
|
283
|
-
- `getLogger(): Logger`
|
|
284
|
-
- `createChildLogger(bindings: Record<string, any>, parentLogger?: Logger): Logger`
|
|
285
|
-
- `createRequestLogger(requestId: string, additionalContext?: Record<string, any>): Logger`
|
|
286
|
-
- `logError(error: Error | unknown, message?: string, context?: Record<string, any>): void`
|
|
287
|
-
- `resetLogger(): void`
|
|
515
|
+
- `getLogger(): Logger` – Get the default logger instance.
|
|
516
|
+
- `createChildLogger(bindings: Record<string, any>, parentLogger?: Logger): Logger` – Create a child logger with bindings.
|
|
517
|
+
- `createRequestLogger(requestId: string, additionalContext?: Record<string, any>): Logger` – Create a logger for a specific request.
|
|
518
|
+
- `logError(error: Error | unknown, message?: string, context?: Record<string, any>): void` – Log an error with optional context.
|
|
519
|
+
- `resetLogger(): void` – Reset the logger to its initial state.
|
|
520
|
+
- `getRedactCensor(): (value: any, paths: string[]) => any` – Get a censor function for redacting sensitive info.
|
|
521
|
+
- `setRedactCensor(censor: (value: any, paths: string[]) => any): void` – Set a custom censor function.
|
|
522
|
+
- `addRedactFields(fields: string[]): void` – Add fields to redact.
|
|
523
|
+
- `setSensitiveFields(): void` – Set the list of sensitive fields to redact.
|
|
524
|
+
- `addSensitiveFields(fields: string[]): void` – Add sensitive fields to redact.
|
|
525
|
+
- `LoggerLevels`: Enum for log levels (e.g., INFO, WARN, ERROR).
|
|
526
|
+
- `Logger`: Interface for the logger instance.
|
|
527
|
+
|
|
528
|
+
**Examples:**
|
|
529
|
+
```ts
|
|
530
|
+
import { getLogger } from "@catbee/utils";
|
|
531
|
+
const logger = getLogger();
|
|
532
|
+
logger.info("App started");
|
|
533
|
+
logger.warn("Potential issue detected");
|
|
534
|
+
logger.error({ context: "some context" }, "Error occurred");
|
|
535
|
+
```
|
|
288
536
|
|
|
289
537
|
## 🧩 Middleware Utilities
|
|
290
538
|
|
|
291
|
-
- `requestId(options?): Middleware`
|
|
292
|
-
- `responseTime(options?): Middleware`
|
|
293
|
-
- `timeout(timeoutMs?: number): Middleware`
|
|
294
|
-
- `setupRequestContext:
|
|
295
|
-
- `errorHandler(options?): Middleware`
|
|
296
|
-
- `validateRequest(schema, location?): Middleware`
|
|
539
|
+
- `requestId(options?): Middleware` – Generate and attach a unique request ID to each request.
|
|
540
|
+
- `responseTime(options?): Middleware` – Measure and log the response time for each request.
|
|
541
|
+
- `timeout(timeoutMs?: number): Middleware` – Abort requests that exceed a specified timeout.
|
|
542
|
+
- `setupRequestContext(): Middleware` – Set up the request context for each incoming request.
|
|
543
|
+
- `errorHandler(options?): Middleware` – Centralized error handling middleware.
|
|
297
544
|
|
|
298
545
|
**Example:**
|
|
299
546
|
```ts
|
|
300
|
-
import { requestId, responseTime, errorHandler } from "@catbee/utils";
|
|
301
|
-
app.use(requestId());
|
|
302
|
-
app.use(responseTime());
|
|
303
|
-
app.use(errorHandler());
|
|
547
|
+
import { Env, requestId, responseTime, errorHandler } from "@catbee/utils";
|
|
548
|
+
app.use(requestId({ headerName: "X-Request-ID", autoLog: true }));
|
|
549
|
+
app.use(responseTime({ addHeaders: true, logOnComplete: true }));
|
|
550
|
+
app.use(errorHandler({ logErrors: true, includeDetails: true }));
|
|
304
551
|
```
|
|
305
552
|
|
|
306
553
|
## 🧩 Object Utilities
|
|
307
554
|
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
- `
|
|
311
|
-
- `
|
|
312
|
-
- `
|
|
313
|
-
- `
|
|
314
|
-
- `
|
|
315
|
-
- `
|
|
316
|
-
- `
|
|
317
|
-
- `isEqual(a: any, b: any): boolean`
|
|
318
|
-
- `filterObject<T>(obj: T, predicate): Partial<T>`
|
|
319
|
-
- `mapObject<T, U>(obj: T, mapFn): Record<keyof T, U>`
|
|
320
|
-
- `deepFreeze<T>(obj: T): Readonly<T>`
|
|
321
|
-
- `isObject(value: unknown): value is Record<string, any>`
|
|
322
|
-
- `getAllPaths(obj: Record<string, any>, parentPath?: string): string[]`
|
|
555
|
+
A set of helpers for working with JavaScript objects, including deep merging, flattening, picking/omitting keys, and more. These utilities help safely manipulate and inspect objects in a type-safe way.
|
|
556
|
+
|
|
557
|
+
- `isObjEmpty(obj: Record<any, any>): boolean` – Check if an object has no own properties.
|
|
558
|
+
- `pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>` – Create a new object with only the specified keys.
|
|
559
|
+
- `omit<T, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>` – Create a new object without the specified keys.
|
|
560
|
+
- `deepObjMerge<T>(target: T, source: Partial<T>): T` – Deeply merge two objects.
|
|
561
|
+
- `flattenObject<T>(obj: T, prefix?: string): Record<string, any>` – Flatten a nested object into dot notation.
|
|
562
|
+
- `getValueByPath<T>(obj: T, path: string): any` – Get a value from an object by dot path.
|
|
563
|
+
- `setValueByPath<T>(obj: T, path: string, value: any): T` – Set a value in an object by dot path.
|
|
564
|
+
- `isEqual(a: any, b: any): boolean` – Deeply compare two values for equality.
|
|
565
|
+
- `filterObject<T>(obj: T, predicate): Partial<T>` – Filter object properties by predicate.
|
|
566
|
+
- `mapObject<T, U>(obj: T, mapFn): Record<keyof T, U>` – Map object values to a new object.
|
|
567
|
+
- `deepFreeze<T>(obj: T): Readonly<T>` – Recursively freeze an object.
|
|
568
|
+
- `isObject(value: unknown): value is Record<string, any>` – Check if a value is a plain object.
|
|
569
|
+
- `getAllPaths(obj: Record<string, any>, parentPath?: string): string[]` – Get all dot paths in an object.
|
|
570
|
+
|
|
571
|
+
**Examples:**
|
|
572
|
+
|
|
573
|
+
```ts
|
|
574
|
+
// Deep merge configurations
|
|
575
|
+
const defaultConfig = {
|
|
576
|
+
server: { port: 3000, host: 'localhost' },
|
|
577
|
+
logging: { level: 'info', format: 'json' }
|
|
578
|
+
};
|
|
579
|
+
|
|
580
|
+
const userConfig = {
|
|
581
|
+
server: { port: 8080 },
|
|
582
|
+
logging: { pretty: true }
|
|
583
|
+
};
|
|
584
|
+
|
|
585
|
+
const finalConfig = deepObjMerge(defaultConfig, userConfig);
|
|
586
|
+
/* Result:
|
|
587
|
+
{
|
|
588
|
+
server: { port: 8080, host: 'localhost' },
|
|
589
|
+
logging: { level: 'info', format: 'json', pretty: true }
|
|
590
|
+
}
|
|
591
|
+
*/
|
|
592
|
+
|
|
593
|
+
// Flatten and unflatten nested objects
|
|
594
|
+
const user = {
|
|
595
|
+
name: 'Alice',
|
|
596
|
+
details: {
|
|
597
|
+
address: {
|
|
598
|
+
city: 'New York',
|
|
599
|
+
zip: '10001'
|
|
600
|
+
},
|
|
601
|
+
preferences: {
|
|
602
|
+
theme: 'dark'
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
|
|
607
|
+
const flat = flattenObject(user);
|
|
608
|
+
/* Result:
|
|
609
|
+
{
|
|
610
|
+
'name': 'Alice',
|
|
611
|
+
'details.address.city': 'New York',
|
|
612
|
+
'details.address.zip': '10001',
|
|
613
|
+
'details.preferences.theme': 'dark'
|
|
614
|
+
}
|
|
615
|
+
*/
|
|
616
|
+
|
|
617
|
+
// Getting and setting values by path
|
|
618
|
+
const theme = getValueByPath(user, 'details.preferences.theme'); // 'dark'
|
|
619
|
+
const updated = setValueByPath(user, 'details.address.state', 'NY');
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
## 📝 Request Utilities
|
|
623
|
+
|
|
624
|
+
Functions for safely parsing, validating, and extracting parameters from HTTP requests.
|
|
625
|
+
|
|
626
|
+
- `parseNumberParam(value: string | undefined, options?: ValidationOptions): ValidationResult<number>` – Parse and validate a numeric parameter from a string.
|
|
627
|
+
- `parseBooleanParam(value: string | undefined, options?: ValidationOptions): ValidationResult<boolean>` – Parse and validate a boolean parameter from a string.
|
|
628
|
+
- `extractPaginationParams(query: Record<string, string | string[]>, defaultPage?: number, defaultLimit?: number, maxLimitSize?: number): { page: number; limit: number }` – Extract and validate pagination parameters from a query object.
|
|
629
|
+
- `extractSortParams(query: Record<string, string | string[]>, allowedFields: string[], defaultSort?): { sortBy: string; sortOrder: 'asc' | 'desc' }` – Extract and validate sorting parameters from a query object.
|
|
630
|
+
- `extractFilterParams(query: Record<string, string | string[]>, allowedFilters: string[]): Record<string, string | string[]>` – Extract filter parameters from a query object based on allowed fields.
|
|
631
|
+
|
|
632
|
+
**Types:**
|
|
633
|
+
```ts
|
|
634
|
+
interface ValidationOptions {
|
|
635
|
+
throwOnError?: boolean;
|
|
636
|
+
errorMessage?: string;
|
|
637
|
+
defaultValue?: any;
|
|
638
|
+
required?: boolean;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
interface ValidationResult<T> {
|
|
642
|
+
isValid: boolean;
|
|
643
|
+
value: T | null;
|
|
644
|
+
error?: string;
|
|
645
|
+
}
|
|
646
|
+
```
|
|
647
|
+
|
|
648
|
+
**Examples:**
|
|
649
|
+
|
|
650
|
+
```ts
|
|
651
|
+
import {
|
|
652
|
+
parseNumberParam,
|
|
653
|
+
parseBooleanParam,
|
|
654
|
+
extractPaginationParams,
|
|
655
|
+
extractSortParams,
|
|
656
|
+
extractFilterParams
|
|
657
|
+
} from '@catbee/utils';
|
|
658
|
+
|
|
659
|
+
// Parse and validate query parameters
|
|
660
|
+
function handleRequest(req, res) {
|
|
661
|
+
// Parse numeric parameter with validation
|
|
662
|
+
const idResult = parseNumberParam(req.query.id, {
|
|
663
|
+
required: true,
|
|
664
|
+
throwOnError: false
|
|
665
|
+
});
|
|
666
|
+
|
|
667
|
+
if (!idResult.isValid) {
|
|
668
|
+
return res.status(400).send({ error: idResult.error });
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// Parse boolean parameter
|
|
672
|
+
const isActiveResult = parseBooleanParam(req.query.isActive, {
|
|
673
|
+
defaultValue: false
|
|
674
|
+
});
|
|
675
|
+
|
|
676
|
+
// Extract standard pagination parameters
|
|
677
|
+
const { page, limit } = extractPaginationParams(
|
|
678
|
+
req.query,
|
|
679
|
+
1, // default page
|
|
680
|
+
20, // default limit
|
|
681
|
+
100 // max limit
|
|
682
|
+
);
|
|
683
|
+
|
|
684
|
+
// Extract sorting parameters
|
|
685
|
+
const { sortBy, sortOrder } = extractSortParams(
|
|
686
|
+
req.query,
|
|
687
|
+
['name', 'createdAt', 'price'], // allowed fields
|
|
688
|
+
{ sortBy: 'createdAt', sortOrder: 'desc' } // defaults
|
|
689
|
+
);
|
|
690
|
+
|
|
691
|
+
// Extract filters based on allowed fields
|
|
692
|
+
const filters = extractFilterParams(
|
|
693
|
+
req.query,
|
|
694
|
+
['category', 'status', 'price']
|
|
695
|
+
);
|
|
696
|
+
|
|
697
|
+
// Process the request with validated parameters
|
|
698
|
+
const items = getItems({
|
|
699
|
+
page,
|
|
700
|
+
limit,
|
|
701
|
+
sortBy,
|
|
702
|
+
sortOrder,
|
|
703
|
+
filters,
|
|
704
|
+
isActive: isActiveResult.value
|
|
705
|
+
});
|
|
706
|
+
|
|
707
|
+
return res.json(items);
|
|
708
|
+
}
|
|
709
|
+
```
|
|
323
710
|
|
|
324
711
|
## 📝 Response Utilities
|
|
325
712
|
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
- `
|
|
329
|
-
- `
|
|
330
|
-
- `
|
|
331
|
-
- `
|
|
332
|
-
- `
|
|
333
|
-
- `
|
|
334
|
-
- `
|
|
335
|
-
- `
|
|
713
|
+
Helpers for creating and sending standardized API responses, including success, error, paginated, and redirect responses. Ensures consistent structure and status codes for all API endpoints.
|
|
714
|
+
|
|
715
|
+
- `SuccessResponse<T>` – Standard API success wrapper object.
|
|
716
|
+
- `ErrorResponse` – Standard API error wrapper object.
|
|
717
|
+
- `PaginatedResponse<T>` – Paginated API response object.
|
|
718
|
+
- `NoContentResponse` – 204 No Content response object.
|
|
719
|
+
- `RedirectResponse` – Redirect response object.
|
|
720
|
+
- `createSuccessResponse<T>(data: T, message?: string): SuccessResponse<T>` – Create a success response.
|
|
721
|
+
- `createErrorResponse(message: string, statusCode?: number): ErrorResponse` – Create an error response.
|
|
722
|
+
- `createPaginatedResponse<T>(allItems: T[], page: number, pageSize: number, message?: string): PaginatedResponse<T>` – Create a paginated response.
|
|
723
|
+
- `sendResponse(res, apiResponse): void` – Send an API response using an HTTP response object.
|
|
724
|
+
- `isApiResponse(value: any): value is ApiResponse<any>` – Check if a value is an API response.
|
|
725
|
+
|
|
726
|
+
**Examples:**
|
|
727
|
+
|
|
728
|
+
```ts
|
|
729
|
+
import {
|
|
730
|
+
createSuccessResponse,
|
|
731
|
+
createErrorResponse,
|
|
732
|
+
createPaginatedResponse,
|
|
733
|
+
sendResponse
|
|
734
|
+
} from "@catbee/utils";
|
|
735
|
+
import express from "express";
|
|
736
|
+
|
|
737
|
+
const app = express();
|
|
738
|
+
|
|
739
|
+
app.get('/api/users', (req, res) => {
|
|
740
|
+
try {
|
|
741
|
+
const allUsers = [/* ...users from database... */];
|
|
742
|
+
const page = parseInt(req.query.page as string) || 1;
|
|
743
|
+
const pageSize = parseInt(req.query.limit as string) || 10;
|
|
744
|
+
|
|
745
|
+
const response = createPaginatedResponse(
|
|
746
|
+
allUsers,
|
|
747
|
+
page,
|
|
748
|
+
pageSize,
|
|
749
|
+
'Users retrieved successfully'
|
|
750
|
+
);
|
|
751
|
+
|
|
752
|
+
sendResponse(res, response);
|
|
753
|
+
} catch (error) {
|
|
754
|
+
const errorResponse = createErrorResponse(
|
|
755
|
+
'Failed to retrieve users',
|
|
756
|
+
500
|
|
757
|
+
);
|
|
758
|
+
sendResponse(res, errorResponse);
|
|
759
|
+
}
|
|
760
|
+
});
|
|
761
|
+
|
|
762
|
+
app.get('/api/profile', (req, res) => {
|
|
763
|
+
const user = { id: 123, name: 'Alice' };
|
|
764
|
+
const response = createSuccessResponse(user, 'Profile retrieved');
|
|
765
|
+
sendResponse(res, response);
|
|
766
|
+
|
|
767
|
+
// This sends:
|
|
768
|
+
// {
|
|
769
|
+
// success: true,
|
|
770
|
+
// data: { id: 123, name: 'Alice' },
|
|
771
|
+
// message: 'Profile retrieved'
|
|
772
|
+
// }
|
|
773
|
+
});
|
|
774
|
+
```
|
|
336
775
|
|
|
337
776
|
## 🧵 String Utilities
|
|
338
777
|
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
- `
|
|
342
|
-
- `
|
|
343
|
-
- `
|
|
344
|
-
- `
|
|
345
|
-
- `
|
|
346
|
-
- `
|
|
347
|
-
- `
|
|
348
|
-
- `
|
|
349
|
-
- `
|
|
350
|
-
- `
|
|
351
|
-
- `
|
|
352
|
-
- `
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
778
|
+
A set of utilities for manipulating, formatting, and transforming strings. Includes helpers for casing, masking, slugifying, truncating, and more.
|
|
779
|
+
|
|
780
|
+
- `capitalize(str: string): string` – Capitalize the first letter of a string.
|
|
781
|
+
- `toKebabCase(str: string): string` – Convert a string to kebab-case.
|
|
782
|
+
- `toCamelCase(str: string): string` – Convert a string to camelCase.
|
|
783
|
+
- `slugify(str: string): string` – Convert a string to a URL-friendly slug.
|
|
784
|
+
- `truncate(str: string, len: number): string` – Truncate a string to a maximum length.
|
|
785
|
+
- `toPascalCase(str: string): string` – Convert a string to PascalCase.
|
|
786
|
+
- `toSnakeCase(str: string): string` – Convert a string to snake_case.
|
|
787
|
+
- `mask(str: string, visibleStart?: number, visibleEnd?: number, maskChar?: string): string` – Mask part of a string for privacy.
|
|
788
|
+
- `stripHtml(str: string): string` – Remove HTML tags from a string.
|
|
789
|
+
- `equalsIgnoreCase(a: string, b: string): boolean` – Compare two strings ignoring case.
|
|
790
|
+
- `reverse(str: string): string` – Reverse the characters in a string.
|
|
791
|
+
- `countOccurrences(str: string, substring: string, caseSensitive?: boolean): number` – Count how many times a substring appears.
|
|
792
|
+
|
|
793
|
+
** Examples **
|
|
794
|
+
```ts
|
|
795
|
+
import { capitalize, toCamelCase, slugify, mask } from "@catbee/utils";
|
|
796
|
+
|
|
797
|
+
const exampleString = "Hello World";
|
|
798
|
+
|
|
799
|
+
console.log(capitalize(exampleString)); // "Hello world"
|
|
800
|
+
console.log(toCamelCase(exampleString)); // "helloWorld"
|
|
801
|
+
console.log(slugify(exampleString)); // "hello-world"
|
|
802
|
+
console.log(mask(exampleString, 2, 5, "*")); // "He***"
|
|
803
|
+
```
|
|
358
804
|
|
|
359
805
|
## 🌐 URL Utilities
|
|
360
806
|
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
- `
|
|
364
|
-
- `
|
|
365
|
-
- `
|
|
366
|
-
- `
|
|
367
|
-
- `
|
|
368
|
-
- `
|
|
369
|
-
- `
|
|
370
|
-
- `
|
|
371
|
-
- `
|
|
807
|
+
Helpers for parsing, validating, building, and manipulating URLs and query strings. Useful for web, API, and routing logic.
|
|
808
|
+
|
|
809
|
+
- `appendQueryParams(url: string, params: Record<string, string | number>): string` – Add query parameters to a URL.
|
|
810
|
+
- `parseQueryString(query: string): Record<string, string>` – Parse a query string into an object.
|
|
811
|
+
- `isValidUrl(url: string, requireHttps?: boolean): boolean` – Check if a string is a valid URL.
|
|
812
|
+
- `getDomain(url: string, removeSubdomains?: boolean): string` – Extract the domain from a URL.
|
|
813
|
+
- `joinPaths(...segments: string[]): string` – Join multiple URL path segments.
|
|
814
|
+
- `normalizeUrl(url: string, base?: string): string` – Normalize a URL, optionally with a base.
|
|
815
|
+
- `createUrlBuilder(baseUrl: string): { path(path: string, params?: Record<string, any>): string; query(params: Record<string, any>): string }` – Build URLs with paths and query parameters.
|
|
816
|
+
- `extractQueryParams(url: string, paramNames: string[]): Record<string, string>` – Extract specific query parameters from a URL.
|
|
817
|
+
- `removeQueryParams(url: string, paramsToRemove: string[]): string` – Remove specific query parameters from a URL.
|
|
818
|
+
- `getExtension(url: string): string` – Get the file extension from a URL.
|
|
819
|
+
- `parseTypedQueryParams<T>(url: string, converters?: Record<keyof T, (val: string) => any>): Partial<T>` – Parse and convert query parameters to typed values.
|
|
372
820
|
|
|
373
821
|
**Example:**
|
|
374
822
|
```ts
|
|
@@ -378,31 +826,30 @@ const url = appendQueryParams('https://example.com', { page: 1, limit: 10 });
|
|
|
378
826
|
|
|
379
827
|
## ✅ Validate Utilities
|
|
380
828
|
|
|
381
|
-
A comprehensive suite of
|
|
382
|
-
|
|
383
|
-
- `isEmail(str: string): boolean`
|
|
384
|
-
- `isUUID(str: string): boolean`
|
|
385
|
-
- `isURL(str: string): boolean`
|
|
386
|
-
- `isPhone(str: string): boolean`
|
|
387
|
-
- `isAlphanumeric(str: string): boolean`
|
|
388
|
-
- `isNumeric(value: string | number): boolean`
|
|
389
|
-
- `isHexColor(str: string): boolean`
|
|
390
|
-
- `isISODate(str: string): boolean`
|
|
391
|
-
- `isLengthBetween(str: string, min: number, max: number): boolean`
|
|
392
|
-
- `isNumberBetween(value: number, min: number, max: number): boolean`
|
|
393
|
-
- `isAlpha(str: string): boolean`
|
|
394
|
-
- `isStrongPassword(str: string): boolean`
|
|
395
|
-
- `isIPv4(str: string): boolean`
|
|
396
|
-
- `isIPv6(str: string): boolean`
|
|
397
|
-
- `isCreditCard(str: string): boolean`
|
|
398
|
-
- `isValidJSON(str: string): boolean`
|
|
399
|
-
- `
|
|
400
|
-
- `
|
|
401
|
-
- `
|
|
402
|
-
- `
|
|
403
|
-
- `
|
|
404
|
-
- `
|
|
405
|
-
- `validateAll(value: unknown, validators: Array<(value: unknown) => boolean>): boolean`
|
|
829
|
+
A comprehensive suite of validators for checking strings, numbers, objects, arrays, and common formats such as email, UUID, IP, and more. Useful for input validation and API parameter checks.
|
|
830
|
+
|
|
831
|
+
- `isEmail(str: string): boolean` – Check if a string is a valid email address.
|
|
832
|
+
- `isUUID(str: string): boolean` – Check if a string is a valid UUID.
|
|
833
|
+
- `isURL(str: string): boolean` – Check if a string is a valid URL.
|
|
834
|
+
- `isPhone(str: string): boolean` – Check if a string is a valid phone number.
|
|
835
|
+
- `isAlphanumeric(str: string): boolean` – Check if a string contains only letters and numbers.
|
|
836
|
+
- `isNumeric(value: string | number): boolean` – Check if a value is numeric.
|
|
837
|
+
- `isHexColor(str: string): boolean` – Check if a string is a valid hex color code.
|
|
838
|
+
- `isISODate(str: string): boolean` – Check if a string is a valid ISO date.
|
|
839
|
+
- `isLengthBetween(str: string, min: number, max: number): boolean` – Check if a string's length is within a range.
|
|
840
|
+
- `isNumberBetween(value: number, min: number, max: number): boolean` – Check if a number is within a range.
|
|
841
|
+
- `isAlpha(str: string): boolean` – Check if a string contains only letters.
|
|
842
|
+
- `isStrongPassword(str: string): boolean` – Check if a string is a strong password.
|
|
843
|
+
- `isIPv4(str: string): boolean` – Check if a string is a valid IPv4 address.
|
|
844
|
+
- `isIPv6(str: string): boolean` – Check if a string is a valid IPv6 address.
|
|
845
|
+
- `isCreditCard(str: string): boolean` – Check if a string is a valid credit card number.
|
|
846
|
+
- `isValidJSON(str: string): boolean` – Check if a string is valid JSON.
|
|
847
|
+
- `isArray<T = unknown>(value: unknown, itemGuard?: (item: unknown) => item is T): value is T[]` – Check if a value is an array (optionally with type guard).
|
|
848
|
+
- `isObject(value: unknown): value is Record<string, unknown>` – Check if a value is a plain object.
|
|
849
|
+
- `hasRequiredProps(obj: Record<string, unknown>, requiredProps: string[]): boolean` – Check if an object has all required properties.
|
|
850
|
+
- `isDateInRange(date: Date, minDate?: Date, maxDate?: Date): boolean` – Check if a date is within a range.
|
|
851
|
+
- `matchesPattern(str: string, pattern: RegExp): boolean` – Check if a string matches a regular expression.
|
|
852
|
+
- `validateAll(value: unknown, validators: Array<(value: unknown) => boolean>): boolean` – Check if all validators pass for a value.
|
|
406
853
|
|
|
407
854
|
---
|
|
408
855
|
|
|
@@ -417,13 +864,15 @@ A comprehensive suite of string/format validators for safe input and API checks.
|
|
|
417
864
|
- `@HttpCode(status)` – Set custom HTTP status code for the response.
|
|
418
865
|
- `@Header(name, value)` – Set custom response headers.
|
|
419
866
|
- `@Before(fn)`, `@After(fn)` – Register before/after hooks for a route handler.
|
|
867
|
+
- `@Redirect({ url?: string, statusCode: number })` – Redirect to a different URL.
|
|
868
|
+
- `@Roles(...roles: string[])` – Restrict access to certain roles - req.user.roles[] should include at least one of the specified roles.
|
|
420
869
|
|
|
421
870
|
## Example Usage
|
|
422
871
|
|
|
423
872
|
```typescript
|
|
424
873
|
import {
|
|
425
874
|
Controller, Get, Post, Use, Query, Param, Body, Req, Res,
|
|
426
|
-
HttpCode, Header, Before, After,
|
|
875
|
+
HttpCode, Header, Before, After, Roles, registerControllers
|
|
427
876
|
} from './src/utils/decorators.utils';
|
|
428
877
|
|
|
429
878
|
// Example middleware
|
|
@@ -448,6 +897,8 @@ class ExampleController {
|
|
|
448
897
|
@Header('X-Example', 'yes')
|
|
449
898
|
@Before(beforeHook)
|
|
450
899
|
@After(afterHook)
|
|
900
|
+
@Roles('admin', 'moderator')
|
|
901
|
+
@Redirect('/https://example.com')
|
|
451
902
|
getItem(
|
|
452
903
|
@Query('q') q: string,
|
|
453
904
|
@Param('id') id: string,
|