@6thbridge/utils 0.3.9-0 → 1.0.1
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/lib/data/rabbitmq/index.js.map +1 -1
- package/lib/index.d.ts +0 -1
- package/lib/index.js +1 -2
- package/lib/index.js.map +1 -1
- package/lib/logger/logger.js.map +1 -1
- package/lib/middlewares/common.d.ts +17 -0
- package/lib/middlewares/common.js +142 -5
- package/lib/middlewares/common.js.map +1 -1
- package/lib/middlewares/express.js +4 -3
- package/lib/middlewares/express.js.map +1 -1
- package/lib/tsconfig.tsbuildinfo +1 -1
- package/lib/types/authentication.entity.d.ts +30 -0
- package/lib/types/authentication.entity.js +10 -0
- package/lib/types/authentication.entity.js.map +1 -0
- package/lib/types/context.entity.d.ts +8 -14
- package/lib/types/context.entity.js +38 -36
- package/lib/types/context.entity.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +347 -47
- package/lib/brokers/index.d.ts +0 -5
- package/lib/brokers/index.js +0 -6
- package/lib/brokers/index.js.map +0 -1
- package/lib/brokers/rabbitmq.d.ts +0 -205
- package/lib/brokers/rabbitmq.js +0 -393
- package/lib/brokers/rabbitmq.js.map +0 -1
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { AuthenticationTypes, ClientEntity, UserEntity } from "../types";
|
|
2
|
+
export type AuthorizationClientResponse = Pick<ClientEntity, 'name' | 'clientId' | 'logo' | 'email' | 'status'>;
|
|
3
|
+
export type AuthorizationUserResponse = Pick<UserEntity, 'clientId' | 'name' | 'email' | 'firstName' | 'lastName' | 'roleId'> & {
|
|
4
|
+
userId: string;
|
|
5
|
+
};
|
|
6
|
+
export declare class ValidateUserAccessDTO {
|
|
7
|
+
domain: string;
|
|
8
|
+
secret: string;
|
|
9
|
+
requestClientId: string;
|
|
10
|
+
contextClientId: string;
|
|
11
|
+
country: string;
|
|
12
|
+
currency: string;
|
|
13
|
+
token: string;
|
|
14
|
+
}
|
|
15
|
+
export declare class ValidateUserAccessResponseDTO {
|
|
16
|
+
domain: string;
|
|
17
|
+
country: string;
|
|
18
|
+
currency: string;
|
|
19
|
+
locale: string;
|
|
20
|
+
requestClientId: string;
|
|
21
|
+
contextClientId: string;
|
|
22
|
+
contextClient: AuthorizationClientResponse;
|
|
23
|
+
requestClient: AuthorizationClientResponse;
|
|
24
|
+
authenticationType: AuthenticationTypes;
|
|
25
|
+
requestUserId: string;
|
|
26
|
+
contextUserId: string;
|
|
27
|
+
requestUser: AuthorizationUserResponse;
|
|
28
|
+
contextUser: AuthorizationUserResponse;
|
|
29
|
+
permissions: string;
|
|
30
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ValidateUserAccessResponseDTO = exports.ValidateUserAccessDTO = void 0;
|
|
4
|
+
class ValidateUserAccessDTO {
|
|
5
|
+
}
|
|
6
|
+
exports.ValidateUserAccessDTO = ValidateUserAccessDTO;
|
|
7
|
+
class ValidateUserAccessResponseDTO {
|
|
8
|
+
}
|
|
9
|
+
exports.ValidateUserAccessResponseDTO = ValidateUserAccessResponseDTO;
|
|
10
|
+
//# sourceMappingURL=authentication.entity.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authentication.entity.js","sourceRoot":"","sources":["../../src/types/authentication.entity.ts"],"names":[],"mappings":";;;AAIA,MAAa,qBAAqB;CAQjC;AARD,sDAQC;AAED,MAAa,6BAA6B;CAezC;AAfD,sEAeC"}
|
|
@@ -2,25 +2,26 @@ import { RequestUserEntity } from './user.entity';
|
|
|
2
2
|
import { RequestClientEntity } from './client.entity';
|
|
3
3
|
import express from 'express';
|
|
4
4
|
import { LoggerInterface } from '../logger';
|
|
5
|
+
import { RabbitMQClient } from '../index';
|
|
6
|
+
import { AuthorizationClientResponse, AuthorizationUserResponse, ValidateUserAccessResponseDTO } from "./authentication.entity";
|
|
5
7
|
export declare const INTERNAL_REQUEST_SOURCE = "internal";
|
|
6
8
|
export declare class ContextEntity {
|
|
7
9
|
requestSource?: string;
|
|
8
10
|
clientId?: string;
|
|
9
11
|
requestClientId?: string;
|
|
10
12
|
contextClientId?: string;
|
|
11
|
-
requestClient?: RequestClientEntity;
|
|
12
|
-
contextClient?: RequestClientEntity;
|
|
13
|
+
requestClient?: RequestClientEntity | AuthorizationClientResponse;
|
|
14
|
+
contextClient?: RequestClientEntity | AuthorizationClientResponse;
|
|
13
15
|
requestId?: string;
|
|
14
16
|
authenticationType?: string;
|
|
15
17
|
permissions?: string[];
|
|
16
|
-
features?: string[];
|
|
17
18
|
os?: string;
|
|
18
19
|
platform?: string;
|
|
19
20
|
version?: string;
|
|
20
21
|
request: express.Request | undefined | any;
|
|
21
22
|
data?: any;
|
|
22
|
-
requestUser?: RequestUserEntity;
|
|
23
|
-
contextUser?: RequestUserEntity;
|
|
23
|
+
requestUser?: RequestUserEntity | AuthorizationUserResponse;
|
|
24
|
+
contextUser?: RequestUserEntity | AuthorizationUserResponse;
|
|
24
25
|
contextUserId?: string;
|
|
25
26
|
requestUserId?: string;
|
|
26
27
|
userId?: string;
|
|
@@ -30,16 +31,9 @@ export declare class ContextEntity {
|
|
|
30
31
|
countryCode?: string;
|
|
31
32
|
locale?: string;
|
|
32
33
|
origin?: string;
|
|
33
|
-
broker?:
|
|
34
|
-
[key: string]: any;
|
|
34
|
+
broker?: RabbitMQClient;
|
|
35
35
|
constructor();
|
|
36
36
|
static fromRequest(req: express.Request): ContextEntity;
|
|
37
|
+
static fromAuthorizationResult(req: express.Request, result: ValidateUserAccessResponseDTO): ContextEntity;
|
|
37
38
|
clone(): this;
|
|
38
|
-
getClientId(): string | undefined;
|
|
39
|
-
createDefaultLogger(): void;
|
|
40
|
-
hasPermission(permission: string): boolean;
|
|
41
|
-
hasFeature(feature: string): boolean;
|
|
42
|
-
getUserId(): string;
|
|
43
|
-
getRequestClientId(): string;
|
|
44
|
-
getContextClientId(): string;
|
|
45
39
|
}
|
|
@@ -33,7 +33,7 @@ class ContextEntity {
|
|
|
33
33
|
this.logger = new logger_1.Logger({});
|
|
34
34
|
}
|
|
35
35
|
static fromRequest(req) {
|
|
36
|
-
var _a, _b, _c, _d
|
|
36
|
+
var _a, _b, _c, _d;
|
|
37
37
|
const context = new ContextEntity();
|
|
38
38
|
context.requestSource = req.headers.source;
|
|
39
39
|
context.authenticationType = req.headers['authentication-type'];
|
|
@@ -49,12 +49,10 @@ class ContextEntity {
|
|
|
49
49
|
context.platform = req.headers.platform;
|
|
50
50
|
context.version = req.headers.version;
|
|
51
51
|
context.request = req;
|
|
52
|
-
context.data = req.body;
|
|
53
52
|
context.currencyCode = req.headers['x-currency-code'];
|
|
54
53
|
context.countryCode = req.headers['x-country-code'];
|
|
55
54
|
context.locale = req.headers['x-locale-id'] || 'en';
|
|
56
55
|
context.permissions = ((_d = req.headers.permissions) === null || _d === void 0 ? void 0 : _d.split(',')) || [];
|
|
57
|
-
context.features = ((_e = req.headers.features) === null || _e === void 0 ? void 0 : _e.split(',')) || [];
|
|
58
56
|
context.logger = new logger_1.Logger({
|
|
59
57
|
requestId: context.requestId,
|
|
60
58
|
requestClientId: context.requestClientId,
|
|
@@ -66,41 +64,45 @@ class ContextEntity {
|
|
|
66
64
|
});
|
|
67
65
|
return context;
|
|
68
66
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
67
|
+
static fromAuthorizationResult(req, result) {
|
|
68
|
+
const context = new ContextEntity();
|
|
69
|
+
context.requestSource = req.headers.source;
|
|
70
|
+
context.authenticationType = result.authenticationType;
|
|
71
|
+
context.requestClientId = result.requestClientId;
|
|
72
|
+
context.contextClientId = result.requestClientId;
|
|
73
|
+
context.requestClient = result.requestClient;
|
|
74
|
+
context.contextUser = result.contextUser;
|
|
75
|
+
context.requestUserId = result.requestUserId;
|
|
76
|
+
context.contextUserId = result.requestUserId;
|
|
77
|
+
context.requestUser = result.requestUser;
|
|
78
|
+
context.contextUser = result.contextUser;
|
|
79
|
+
context.requestId = req.headers['x-request-id'] || (0, crypto_1.randomUUID)();
|
|
80
|
+
context.ip = req.headers['cf-connecting-ip'] || req.ip;
|
|
81
|
+
context.os = req.headers.os;
|
|
82
|
+
context.platform = req.headers.platform;
|
|
83
|
+
context.version = req.headers.version;
|
|
84
|
+
context.request = req;
|
|
85
|
+
context.currencyCode = req.headers['x-currency-code'] || result.currency;
|
|
86
|
+
context.countryCode = req.headers['x-country-code'] || result.country;
|
|
87
|
+
context.locale = req.headers['x-locale-id'] || result.locale || 'en';
|
|
88
|
+
context.permissions = result.permissions.split(",") || [];
|
|
89
|
+
context.logger = new logger_1.Logger({
|
|
90
|
+
requestId: context.requestId,
|
|
91
|
+
requestClientId: context.requestClientId,
|
|
92
|
+
contextClientId: context.contextClientId,
|
|
93
|
+
userId: context.requestUserId,
|
|
94
|
+
ip: context.ip,
|
|
95
|
+
url: context.request.originalUrl,
|
|
96
|
+
requestSource: context.requestSource,
|
|
85
97
|
});
|
|
98
|
+
//Deprecated fields
|
|
99
|
+
context.data = req.body;
|
|
100
|
+
context.userId = result.requestUserId;
|
|
101
|
+
context.clientId = result.requestClientId;
|
|
102
|
+
return context;
|
|
86
103
|
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
return ((_a = this.permissions) === null || _a === void 0 ? void 0 : _a.includes(permission)) || false;
|
|
90
|
-
}
|
|
91
|
-
hasFeature(feature) {
|
|
92
|
-
var _a;
|
|
93
|
-
return ((_a = this.features) === null || _a === void 0 ? void 0 : _a.includes(feature)) || false;
|
|
94
|
-
}
|
|
95
|
-
getUserId() {
|
|
96
|
-
var _a, _b;
|
|
97
|
-
return ((_a = this === null || this === void 0 ? void 0 : this.contextUser) === null || _a === void 0 ? void 0 : _a.userId) || ((_b = this === null || this === void 0 ? void 0 : this.requestUser) === null || _b === void 0 ? void 0 : _b.userId) || (this === null || this === void 0 ? void 0 : this.userId) || '';
|
|
98
|
-
}
|
|
99
|
-
getRequestClientId() {
|
|
100
|
-
return this.requestClientId || this.clientId || '';
|
|
101
|
-
}
|
|
102
|
-
getContextClientId() {
|
|
103
|
-
return this.contextClientId || this.clientId || '';
|
|
104
|
+
clone() {
|
|
105
|
+
return _.cloneDeep(this);
|
|
104
106
|
}
|
|
105
107
|
}
|
|
106
108
|
exports.ContextEntity = ContextEntity;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.entity.js","sourceRoot":"","sources":["../../src/types/context.entity.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAA4B;AAK5B,mCAAoC;AACpC,6CAA0C;
|
|
1
|
+
{"version":3,"file":"context.entity.js","sourceRoot":"","sources":["../../src/types/context.entity.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAA4B;AAK5B,mCAAoC;AACpC,6CAA0C;AAO7B,QAAA,uBAAuB,GAAG,UAAU,CAAC;AAElD,MAAa,aAAa;IA4BxB;QACE,IAAI,CAAC,MAAM,GAAG,IAAI,eAAM,CAAC,EAAE,CAAC,CAAC;IAC/B,CAAC;IAED,MAAM,CAAC,WAAW,CAAC,GAAoB;;QACrC,MAAM,OAAO,GAAG,IAAI,aAAa,EAAE,CAAC;QACpC,OAAO,CAAC,aAAa,GAAG,GAAG,CAAC,OAAO,CAAC,MAAgB,CAAC;QACrD,OAAO,CAAC,kBAAkB,GAAG,GAAG,CAAC,OAAO,CAAC,qBAAqB,CAAW,CAAC;QAC1E,OAAO,CAAC,QAAQ,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAW,CAAC;QAC5F,OAAO,CAAC,eAAe,GAAG,CAA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C3B,CAAC;CACF;AA7GD,sCA6GC"}
|
package/package.json
CHANGED
package/readme.md
CHANGED
|
@@ -1,79 +1,379 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @6thbridge/utils Documentation
|
|
2
|
+
[](https://badge.fury.io/js/%406thbridge%2Futils)[](https://opensource.org/licenses/ISC)
|
|
3
|
+
A comprehensive TypeScript utility library for Node.js applications, providing reusable components for common development tasks including database operations, caching, messaging, logging, and more.
|
|
4
|
+
## Table of Contents
|
|
5
|
+
- [Installation](#installation)
|
|
6
|
+
- [Quick Start](#quick-start)
|
|
7
|
+
- [Core Modules](#core-modules)
|
|
8
|
+
- [API Reference](#api-reference)
|
|
9
|
+
- [Examples](#examples)
|
|
10
|
+
- [Testing](#testing)
|
|
11
|
+
- [Contributing](#contributing)
|
|
12
|
+
- [License](#license)
|
|
4
13
|
|
|
5
14
|
## Installation
|
|
15
|
+
``` bash
|
|
16
|
+
# Using npm
|
|
17
|
+
npm install @6thbridge/utils
|
|
6
18
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
"@6thbridge/utils": "^0.2.34" // see the "releases" section
|
|
10
|
-
}
|
|
19
|
+
# Using yarn
|
|
20
|
+
yarn add @6thbridge/utils
|
|
11
21
|
```
|
|
22
|
+
### Dependencies
|
|
23
|
+
This package includes the following key dependencies:
|
|
24
|
+
- **Database**: `mongoose`, , `ioredis` `mongoose-paginate-v2`
|
|
25
|
+
- **Messaging**: `amqplib`, , `kafkajs` `amqp-connection-manager`
|
|
26
|
+
- **Utilities**: `lodash`, `dayjs`, `joi`, `axios`
|
|
27
|
+
- **Monitoring**: , `rollbar` `@opentelemetry/auto-instrumentations-node`
|
|
28
|
+
|
|
29
|
+
## Quick Start
|
|
30
|
+
``` typescript
|
|
31
|
+
import {
|
|
32
|
+
HelperUtil,
|
|
33
|
+
ReferenceUtil,
|
|
34
|
+
RedisClient,
|
|
35
|
+
RabbitMQClient,
|
|
36
|
+
MongoDBRepository,
|
|
37
|
+
logger
|
|
38
|
+
} from '@6thbridge/utils';
|
|
12
39
|
|
|
13
|
-
|
|
40
|
+
// Generate a reference
|
|
41
|
+
const reference = ReferenceUtil.generateReference('production');
|
|
14
42
|
|
|
15
|
-
|
|
43
|
+
// Use Redis
|
|
44
|
+
const redis = RedisClient.getInstance();
|
|
45
|
+
await redis.connect({ url: 'redis://localhost:6379' });
|
|
16
46
|
|
|
17
|
-
|
|
18
|
-
const
|
|
47
|
+
// Clean data
|
|
48
|
+
const cleanData = HelperUtil.removeFieldsWithEmptyValue(data);
|
|
49
|
+
|
|
50
|
+
// Log information
|
|
51
|
+
logger.info('Application started', { reference });
|
|
19
52
|
```
|
|
53
|
+
## Core Modules
|
|
54
|
+
### 🔧 [Utilities](./src/utils/README.md)
|
|
55
|
+
Essential utility functions for data manipulation, reference generation, and common operations.
|
|
56
|
+
- **HelperUtil**: Data cleaning, activity logging, async utilities
|
|
57
|
+
- **ReferenceUtil**: Reference and UUID generation
|
|
58
|
+
- **Phone Number Formatting**: International phone number formatting
|
|
20
59
|
|
|
21
|
-
###
|
|
60
|
+
### 🗄️ [Database](./src/database/README.md)
|
|
61
|
+
Database abstraction layers and repository patterns.
|
|
62
|
+
- **MongoDBRepository**: MongoDB operations with Mongoose
|
|
63
|
+
- **Redis Integration**: Caching and session management
|
|
22
64
|
|
|
23
|
-
|
|
65
|
+
### 📨 [Brokers](./src/brokers/README.md)
|
|
66
|
+
Message broker implementations for event-driven architecture.
|
|
67
|
+
- **RabbitMQClient**: AMQP messaging with RabbitMQ
|
|
68
|
+
- **KafkaJS Integration**: Apache Kafka message streaming
|
|
24
69
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
70
|
+
### 💾 [Cache](./src/cache/README.md)
|
|
71
|
+
Caching solutions for improved performance.
|
|
72
|
+
- **RedisClient**: Redis-based caching with clustering support
|
|
73
|
+
- **Node-Cache**: In-memory caching for lightweight applications
|
|
74
|
+
|
|
75
|
+
### 📝 [Logger](./src/logger/README.md)
|
|
76
|
+
Comprehensive logging system with multiple levels and integrations.
|
|
77
|
+
- **Structured Logging**: JSON-formatted logs
|
|
78
|
+
- **Multiple Transports**: Console, file, and external service logging
|
|
79
|
+
- **Error Tracking**: Integration with monitoring services
|
|
80
|
+
|
|
81
|
+
### 🛡️ [Middlewares](./src/middlewares/README.md)
|
|
82
|
+
Express.js middlewares for common functionality.
|
|
83
|
+
- **Authentication**: JWT and API key validation
|
|
84
|
+
- **Validation**: Request/response validation
|
|
85
|
+
- **Error Handling**: Centralized error processing
|
|
86
|
+
|
|
87
|
+
### 📊 [Monitoring](./src/monitoring/README.md)
|
|
88
|
+
Application monitoring and observability tools.
|
|
89
|
+
- **OpenTelemetry**: Distributed tracing
|
|
90
|
+
- **Rollbar Integration**: Error monitoring and alerting
|
|
91
|
+
|
|
92
|
+
## API Reference
|
|
93
|
+
### HelperUtil
|
|
94
|
+
``` typescript
|
|
95
|
+
class HelperUtil {
|
|
96
|
+
// Async utility
|
|
97
|
+
static async sleep(durationInMs: number = 1000): Promise<void>
|
|
98
|
+
|
|
99
|
+
// Data cleaning
|
|
100
|
+
static removeFieldsWithEmptyValue(value: any): any
|
|
101
|
+
|
|
102
|
+
// Activity logging
|
|
103
|
+
static async saveActivityLog(activityLog: SaveActivityLogDTO, options?: any): Promise<void>
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
### ReferenceUtil
|
|
107
|
+
``` typescript
|
|
108
|
+
class ReferenceUtil {
|
|
109
|
+
// Generate environment-specific reference
|
|
110
|
+
static generateReference(env: string): string
|
|
111
|
+
|
|
112
|
+
// Generate reference with custom prefix
|
|
113
|
+
static generateReferenceWithPrefix(env: string, prefix: string): string
|
|
114
|
+
|
|
115
|
+
// Generate UUID
|
|
116
|
+
static generateUUID(options?: any): string
|
|
117
|
+
}
|
|
29
118
|
```
|
|
119
|
+
### RedisClient
|
|
120
|
+
``` typescript
|
|
121
|
+
class RedisClient {
|
|
122
|
+
// Singleton pattern
|
|
123
|
+
static getInstance(): RedisClient
|
|
124
|
+
static resetInstance(): void
|
|
125
|
+
|
|
126
|
+
// Connection management
|
|
127
|
+
connect(config?: RedisConnect): Commander
|
|
128
|
+
|
|
129
|
+
// Redis operations
|
|
130
|
+
static getRedis(): Commander
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
### RabbitMQClient
|
|
134
|
+
``` typescript
|
|
135
|
+
class RabbitMQClient {
|
|
136
|
+
// Singleton pattern
|
|
137
|
+
static getInstance(): RabbitMQClient
|
|
138
|
+
static resetInstance(): void
|
|
139
|
+
|
|
140
|
+
// Connection and messaging
|
|
141
|
+
connect(config: RabbitMQConnectConfig): AmqpConnectionManager
|
|
142
|
+
static async sendToQueue(queueName: string, payload: any, options?: PublishOptions): Promise<any>
|
|
143
|
+
static async publishToExchange(exchangeName: string, routeKey: string, payload: any, options?: PublishOptions): Promise<any>
|
|
144
|
+
|
|
145
|
+
// Message consumption
|
|
146
|
+
static listen(queueName: string, options: any, callback: Function): Promise<void>
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
### MongoDBRepository
|
|
150
|
+
``` typescript
|
|
151
|
+
class MongoDBRepository {
|
|
152
|
+
constructor(Model: TypedModel<any>)
|
|
153
|
+
|
|
154
|
+
// CRUD operations
|
|
155
|
+
create(payload: Record<string, any>, options?: CreateOptions): Promise<any>
|
|
156
|
+
findById(id: string, projection?: ProjectionType<any>, options?: QueryOptions): Promise<any>
|
|
157
|
+
findOne(condition: Record<string, any>, sort?: Record<string, number>, options?: FindOptions): Promise<any>
|
|
158
|
+
find(condition: Record<string, any>, sort?: Record<string, any>, options?: FindOptions): Promise<any>
|
|
159
|
+
|
|
160
|
+
// Advanced operations
|
|
161
|
+
paginate(condition: Record<string, any>, sort?: Record<string, any>, options?: FindOptions): Promise<PaginateResult<any>>
|
|
162
|
+
updateOne(query: Record<string, any>, update: Record<string, any>, options?: MongooseOptions): Promise<any>
|
|
163
|
+
bulkWrite(bulkWritePayload: any): Promise<any>
|
|
164
|
+
}
|
|
165
|
+
```
|
|
166
|
+
## Examples
|
|
167
|
+
### Basic Usage Examples
|
|
168
|
+
#### Data Cleaning
|
|
169
|
+
``` typescript
|
|
170
|
+
import { HelperUtil } from '@6thbridge/utils';
|
|
30
171
|
|
|
31
|
-
|
|
172
|
+
const dirtyData = {
|
|
173
|
+
name: 'John Doe',
|
|
174
|
+
email: '',
|
|
175
|
+
phone: null,
|
|
176
|
+
address: undefined,
|
|
177
|
+
age: 30
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
const cleanData = HelperUtil.removeFieldsWithEmptyValue(dirtyData);
|
|
181
|
+
// Result: { name: 'John Doe', age: 30 }
|
|
182
|
+
```
|
|
183
|
+
#### Reference Generation
|
|
184
|
+
``` typescript
|
|
185
|
+
import { ReferenceUtil } from '@6thbridge/utils';
|
|
186
|
+
|
|
187
|
+
// Production reference
|
|
188
|
+
const prodRef = ReferenceUtil.generateReference('production');
|
|
189
|
+
// Example: L20240101120000ABCDE
|
|
190
|
+
|
|
191
|
+
// Development reference with prefix
|
|
192
|
+
const devRef = ReferenceUtil.generateReferenceWithPrefix('development', 'ORDER');
|
|
193
|
+
// Example: DORDER20240101120000ABCDE
|
|
194
|
+
```
|
|
195
|
+
#### Redis Operations
|
|
196
|
+
``` typescript
|
|
197
|
+
import { RedisClient } from '@6thbridge/utils';
|
|
32
198
|
|
|
33
|
-
|
|
199
|
+
async function cacheExample() {
|
|
200
|
+
const redis = RedisClient.getInstance();
|
|
201
|
+
redis.connect({
|
|
202
|
+
url: 'redis://localhost:6379',
|
|
203
|
+
keepAlive: true
|
|
204
|
+
});
|
|
34
205
|
|
|
35
|
-
|
|
206
|
+
// Cache operations
|
|
207
|
+
await RedisClient.getRedis().set('user:123', JSON.stringify({ name: 'John' }));
|
|
208
|
+
const user = await RedisClient.getRedis().get('user:123');
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
#### Message Queue
|
|
212
|
+
``` typescript
|
|
213
|
+
import { RabbitMQClient } from '@6thbridge/utils';
|
|
214
|
+
|
|
215
|
+
async function messagingExample() {
|
|
216
|
+
const broker = RabbitMQClient.getInstance();
|
|
217
|
+
broker.connect({
|
|
218
|
+
url: 'amqp://localhost:5672',
|
|
219
|
+
queues: [
|
|
220
|
+
{ queueName: 'user.created' }
|
|
221
|
+
],
|
|
222
|
+
exchanges: [],
|
|
223
|
+
exchangeBindings: []
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
// Send message
|
|
227
|
+
await RabbitMQClient.sendToQueue('user.created', {
|
|
228
|
+
userId: '123',
|
|
229
|
+
event: 'USER_CREATED',
|
|
230
|
+
timestamp: new Date()
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
// Listen for messages
|
|
234
|
+
RabbitMQClient.listen('user.created', {}, (message, options) => {
|
|
235
|
+
console.log('Received:', JSON.parse(message));
|
|
236
|
+
options.ack();
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
```
|
|
240
|
+
### Phone Number Formatting
|
|
241
|
+
``` typescript
|
|
242
|
+
import { formatPhoneNumber, formatPhoneNumberArray } from '@6thbridge/utils';
|
|
243
|
+
|
|
244
|
+
// Single phone number
|
|
245
|
+
let phoneNumber = '08012345678';
|
|
246
|
+
phoneNumber = formatPhoneNumber(phoneNumber, 'NG');
|
|
247
|
+
console.log(phoneNumber); // 2348012345678
|
|
248
|
+
|
|
249
|
+
// Multiple phone numbers
|
|
36
250
|
let phoneNumbers = ['08012345678', '08012345679'];
|
|
37
|
-
phoneNumbers =
|
|
38
|
-
console.log(phoneNumbers); //['2348012345678','2348012345679']
|
|
251
|
+
phoneNumbers = formatPhoneNumberArray(phoneNumbers, 'NG');
|
|
252
|
+
console.log(phoneNumbers); // ['2348012345678', '2348012345679']
|
|
39
253
|
```
|
|
254
|
+
### Logging
|
|
255
|
+
``` typescript
|
|
256
|
+
import { logger } from '@6thbridge/utils';
|
|
40
257
|
|
|
41
|
-
|
|
258
|
+
// Different log levels
|
|
259
|
+
logger.error('Database connection failed', { error: 'Connection refused' });
|
|
260
|
+
logger.warn('High memory usage detected', { usage: '85%' });
|
|
261
|
+
logger.info('User logged in', { userId: '123' });
|
|
262
|
+
logger.debug('Processing request', { requestId: 'req-456' });
|
|
42
263
|
|
|
43
|
-
|
|
264
|
+
// Exception logging
|
|
265
|
+
try {
|
|
266
|
+
// risky operation
|
|
267
|
+
} catch (error) {
|
|
268
|
+
logger.exception(error, { context: 'user-registration' });
|
|
269
|
+
}
|
|
270
|
+
```
|
|
271
|
+
## Environment Variables
|
|
272
|
+
The library supports various environment variables for configuration:
|
|
273
|
+
``` bash
|
|
274
|
+
# Redis Configuration
|
|
275
|
+
REDIS_HOST=127.0.0.1
|
|
276
|
+
REDIS_PORT=6379
|
|
277
|
+
REDIS_PASSWORD=your_password
|
|
278
|
+
REDIS_URL=redis://localhost:6379
|
|
279
|
+
REDIS_CLUSTER_URL=redis://node1:6379,redis://node2:6379
|
|
44
280
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
281
|
+
# RabbitMQ Configuration
|
|
282
|
+
RABBITMQ_URL=amqp://localhost:5672
|
|
283
|
+
RABBITMQ_CLUSTER_URL=amqp://node1:5672,amqp://node2:5672
|
|
284
|
+
|
|
285
|
+
# Application Configuration
|
|
286
|
+
APP_NAME=your-app-name
|
|
287
|
+
TZ=Africa/Lagos
|
|
288
|
+
LOG_OUT=1
|
|
289
|
+
|
|
290
|
+
# Service URLs
|
|
291
|
+
USER_SERVICE_URL=http://user-service:3000
|
|
52
292
|
```
|
|
293
|
+
## Testing
|
|
294
|
+
The library includes comprehensive test suites using Jest:
|
|
295
|
+
``` bash
|
|
296
|
+
# Run all tests
|
|
297
|
+
yarn test
|
|
53
298
|
|
|
54
|
-
|
|
299
|
+
# Run tests in watch mode
|
|
300
|
+
yarn test --watch
|
|
55
301
|
|
|
56
|
-
|
|
302
|
+
# Run tests with coverage
|
|
303
|
+
yarn test --coverage
|
|
57
304
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
logger.warn('This is an warning message from the package', { foo: 'bar' }, new Error().stack);
|
|
61
|
-
logger.debug('This is an debug message from the package', { foo: 'bar' }, new Error().stack);
|
|
62
|
-
logger.critical('This is a critical message from the package', { foo: 'bar' }, new Error().stack);
|
|
63
|
-
logger.info('This is a info message from the package', { foo: 'bar' }, new Error().stack);
|
|
64
|
-
logger.exception(new Error('Custom Error'), { foo: 'bar' }, new Error().stack);
|
|
65
|
-
logger.out(new Error('Custom Error'), { foo: 'bar' }, new Error().stack); //to console, only logs out when LOG_OUT=1
|
|
305
|
+
# Run specific test file
|
|
306
|
+
yarn test reference.util.test.ts
|
|
66
307
|
```
|
|
308
|
+
### Writing Tests
|
|
309
|
+
``` typescript
|
|
310
|
+
import { ReferenceUtil } from '@6thbridge/utils';
|
|
67
311
|
|
|
68
|
-
|
|
312
|
+
describe('ReferenceUtil', () => {
|
|
313
|
+
it('should generate production reference', () => {
|
|
314
|
+
const ref = ReferenceUtil.generateReference('production');
|
|
315
|
+
expect(ref).toMatch(/^L\d{14}[A-Z]{5}$/);
|
|
316
|
+
});
|
|
317
|
+
});
|
|
318
|
+
```
|
|
319
|
+
## TypeScript Support
|
|
320
|
+
This library is written in TypeScript and provides full type definitions:
|
|
321
|
+
``` typescript
|
|
322
|
+
import {
|
|
323
|
+
RedisConnect,
|
|
324
|
+
RabbitMQConnectConfig,
|
|
325
|
+
SaveActivityLogDTO,
|
|
326
|
+
MongooseOptions
|
|
327
|
+
} from '@6thbridge/utils';
|
|
69
328
|
|
|
70
|
-
|
|
329
|
+
// Type-safe configuration
|
|
330
|
+
const redisConfig: RedisConnect = {
|
|
331
|
+
url: 'redis://localhost:6379',
|
|
332
|
+
keepAlive: true,
|
|
333
|
+
heartbeat: 30
|
|
334
|
+
};
|
|
335
|
+
```
|
|
336
|
+
## Performance Considerations
|
|
337
|
+
- **Connection Pooling**: Redis and RabbitMQ clients use connection pooling
|
|
338
|
+
- **Singleton Pattern**: Database and cache clients follow singleton pattern
|
|
339
|
+
- **Lazy Loading**: Connections are established only when needed
|
|
340
|
+
- **Memory Management**: Proper cleanup and connection closing
|
|
71
341
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
342
|
+
## Error Handling
|
|
343
|
+
The library implements comprehensive error handling:
|
|
344
|
+
``` typescript
|
|
345
|
+
try {
|
|
346
|
+
await RedisClient.getRedis().set('key', 'value');
|
|
347
|
+
} catch (error) {
|
|
348
|
+
logger.exception(error, { operation: 'redis-set' });
|
|
349
|
+
}
|
|
75
350
|
```
|
|
351
|
+
## Contributing
|
|
352
|
+
1. Fork the repository
|
|
353
|
+
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
|
|
354
|
+
3. Commit your changes (`git commit -m 'Add amazing feature'`)
|
|
355
|
+
4. Push to the branch (`git push origin feature/amazing-feature`)
|
|
356
|
+
5. Open a Pull Request
|
|
357
|
+
|
|
358
|
+
### Development Setup
|
|
359
|
+
``` bash
|
|
360
|
+
# Clone repository
|
|
361
|
+
git clone https://github.com/6thbridge/utils.git
|
|
362
|
+
|
|
363
|
+
# Install dependencies
|
|
364
|
+
yarn install
|
|
76
365
|
|
|
77
|
-
|
|
366
|
+
# Run tests
|
|
367
|
+
yarn test
|
|
78
368
|
|
|
369
|
+
# Build library
|
|
370
|
+
yarn build
|
|
371
|
+
```
|
|
372
|
+
## License
|
|
373
|
+
This project is licensed under the ISC License.
|
|
374
|
+
## Contributors
|
|
79
375
|
- [Micheal Akinwonmi](https://github.com/blackhades)
|
|
376
|
+
|
|
377
|
+
## Support
|
|
378
|
+
For support and questions, please open an issue on the GitHub repository.
|
|
379
|
+
**Note**: This library is actively maintained and used in production environments. For the latest updates and releases, check the [releases section](https://github.com/6thbridge/utils/releases).
|
package/lib/brokers/index.d.ts
DELETED
package/lib/brokers/index.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.RabbitMQ = void 0;
|
|
4
|
-
const rabbitmq_1 = require("./rabbitmq");
|
|
5
|
-
Object.defineProperty(exports, "RabbitMQ", { enumerable: true, get: function () { return rabbitmq_1.RabbitMQ; } });
|
|
6
|
-
//# sourceMappingURL=index.js.map
|