Skip to content

Commit 684ab5a

Browse files
sairanjitKambleSahil3
authored andcommitted
refactor: create common package in libs (#1167)
* refactor: merge nats-interceptor into common Signed-off-by: Sai Ranjit Tummalapalli <[email protected]> * refactor: merge repsonses lib into common Signed-off-by: Sai Ranjit Tummalapalli <[email protected]> * refactor: create common function to handle errors Signed-off-by: Sai Ranjit Tummalapalli <[email protected]> * chore: add todo Signed-off-by: Sai Ranjit Tummalapalli <[email protected]> * refactor: create common package in libs Signed-off-by: Sai Ranjit Tummalapalli <[email protected]> * fix: remove missed image service Signed-off-by: Sai Ranjit Tummalapalli <[email protected]> * refactor: common service Signed-off-by: Sai Ranjit Tummalapalli <[email protected]> --------- Signed-off-by: Sai Ranjit Tummalapalli <[email protected]> Signed-off-by: Sahil Kamble <[email protected]>
1 parent 773276f commit 684ab5a

13 files changed

+321
-202
lines changed

libs/aws/package.json

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,9 @@
33
"main": "src/index",
44
"types": "src/index",
55
"version": "0.0.1",
6-
"files": ["dist"],
7-
"license": "Apache-2.0",
8-
"publishConfig": {
9-
"access": "public"
10-
},
6+
"files": [
7+
"dist"
8+
],
119
"scripts": {
1210
"build": "pnpm run clean && pnpm run compile",
1311
"clean": "rimraf ../../dist/libs/aws",

libs/common/package.json

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
{
2+
"name": "@credebl/common",
3+
"main": "src/index",
4+
"types": "src/index",
5+
"version": "0.0.1",
6+
"files": [
7+
"dist"
8+
],
9+
"scripts": {
10+
"build": "pnpm run clean && pnpm run compile",
11+
"clean": "rimraf ../../dist/libs/common",
12+
"compile": "tsc -p tsconfig.build.json",
13+
"test": "jest"
14+
},
15+
"dependencies": {
16+
"@nestjs/axios": "^3.0.0",
17+
"@nestjs/common": "^10.2.7",
18+
"@nestjs/core": "^10.1.3",
19+
"@nestjs/testing": "^10.1.3",
20+
"@nestjs/microservices": "^10.1.3",
21+
"@nestjs/swagger": "^7.1.6",
22+
"@prisma/client": "^5.1.1",
23+
"@sendgrid/mail": "^7.7.0",
24+
"class-transformer": "^0.5.1",
25+
"class-validator": "^0.14.0",
26+
"crypto-js": "^4.1.1",
27+
"dotenv": "^16.0.3",
28+
"nats": "^2.15.1",
29+
"rxjs": "^7.8.1",
30+
"uuid": "^9.0.0"
31+
},
32+
"devDependencies": {
33+
"@types/crypto-js": "^4.1.1",
34+
"reflect-metadata": "^0.1.13",
35+
"rimraf": "^4.4.0",
36+
"typescript": "^5.1.6"
37+
}
38+
}

libs/common/src/NATSClient.ts

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,16 @@ import { ClientProxy, NatsRecordBuilder } from '@nestjs/microservices';
55
import { map } from 'rxjs/operators';
66
import * as nats from 'nats';
77
import { firstValueFrom } from 'rxjs';
8-
import ContextStorageService, { ContextStorageServiceKey } from '@credebl/context/contextStorageService.interface';
8+
import ContextStorageService, { ContextStorageServiceKey } from '../../context/src/contextStorageService.interface';
99
import { v4 } from 'uuid';
1010

1111
@Injectable()
1212
export class NATSClient {
1313
private readonly logger: Logger;
14-
constructor(@Inject(ContextStorageServiceKey)
15-
private readonly contextStorageService: ContextStorageService
16-
) {
14+
constructor(
15+
@Inject(ContextStorageServiceKey)
16+
private readonly contextStorageService: ContextStorageService
17+
) {
1718
this.logger = new Logger('NATSClient');
1819
}
1920

@@ -22,7 +23,7 @@ export class NATSClient {
2223
this.logger.log(`Inside NATSClient for sendNats()`);
2324
const pattern = { cmd };
2425
const headers = nats.headers(1, this.contextStorageService.getContextId());
25-
const record = new NatsRecordBuilder(payload).setHeaders(headers).build();
26+
const record = new NatsRecordBuilder(payload).setHeaders(headers).build();
2627

2728
return serviceProxy
2829
.send<string>(pattern, record)
@@ -34,29 +35,28 @@ export class NATSClient {
3435
.toPromise();
3536
}
3637

38+
sendNatsMessage(serviceProxy: ClientProxy, cmd: string, payload: any): Promise<any> {
39+
const pattern = { cmd };
40+
const headers = nats.headers(1, this.contextStorageService.getContextId());
41+
const record = new NatsRecordBuilder(payload).setHeaders(headers).build();
3742

38-
sendNatsMessage(serviceProxy: ClientProxy, cmd: string, payload: any): Promise<any> {
39-
const pattern = { cmd };
40-
const headers = nats.headers(1, this.contextStorageService.getContextId());
41-
const record = new NatsRecordBuilder(payload).setHeaders(headers).build();
42-
43-
const result = serviceProxy.send<string>(pattern, record);
43+
const result = serviceProxy.send<string>(pattern, record);
4444

45-
return firstValueFrom(result);
46-
}
45+
return firstValueFrom(result);
46+
}
4747

48-
send<T>(serviceProxy: ClientProxy, pattern: object, payload: any): Promise<T> {
49-
let contextId = this.contextStorageService.getContextId();
48+
send<T>(serviceProxy: ClientProxy, pattern: object, payload: any): Promise<T> {
49+
let contextId = this.contextStorageService.getContextId();
5050

51-
if (!contextId) {
52-
contextId = v4();
53-
}
51+
if (!contextId) {
52+
contextId = v4();
53+
}
5454

55-
const headers = nats.headers(1, contextId);
56-
const record = new NatsRecordBuilder(payload).setHeaders(headers).build();
55+
const headers = nats.headers(1, contextId);
56+
const record = new NatsRecordBuilder(payload).setHeaders(headers).build();
5757

58-
const result = serviceProxy.send<T>(pattern, record);
58+
const result = serviceProxy.send<T>(pattern, record);
5959

60-
return firstValueFrom(result);
60+
return firstValueFrom(result);
61+
}
6162
}
62-
}

libs/common/src/cast.helper.ts

Lines changed: 35 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
import { DidMethod, JSONSchemaType, ledgerLessDIDType, ProofType, schemaRequestType, TemplateIdentifier } from '@credebl/enum/enum';
1+
import {
2+
DidMethod,
3+
JSONSchemaType,
4+
ledgerLessDIDType,
5+
ProofType,
6+
schemaRequestType,
7+
TemplateIdentifier
8+
} from '../../enum/src/enum';
29
import { ISchemaFields } from './interfaces/schema.interface';
310
import { BadRequestException, PipeTransform } from '@nestjs/common';
411
import { plainToClass } from 'class-transformer';
@@ -82,19 +89,22 @@ export function isSafeString(value: string): boolean {
8289
}
8390

8491
export const IsNotSQLInjection =
85-
(validationOptions?: ValidationOptions): PropertyDecorator => (object: object, propertyName: string) => {
92+
(validationOptions?: ValidationOptions): PropertyDecorator =>
93+
(object: object, propertyName: string) => {
8694
registerDecorator({
8795
name: 'isNotSQLInjection',
8896
target: object.constructor,
8997
propertyName,
9098
options: validationOptions,
9199
validator: {
92100
validate(value) {
93-
94101
// Check if the value is a string
95102
if ('string' === typeof value) {
96103
// Regex to check for SQL injection keywords at the start
97-
const startInjectionRegex = new RegExp(`^\\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|ALTER|CREATE|EXEC|FROM|WHERE|AND|OR)\\b`, 'i');
104+
const startInjectionRegex = new RegExp(
105+
`^\\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|ALTER|CREATE|EXEC|FROM|WHERE|AND|OR)\\b`,
106+
'i'
107+
);
98108

99109
// Check if the SQL injection pattern is present at the start
100110
if (startInjectionRegex.test(value)) {
@@ -110,7 +120,7 @@ export const IsNotSQLInjection =
110120
}
111121
});
112122
};
113-
123+
114124
@ValidatorConstraint({ name: 'customText', async: false })
115125
export class ImageBase64Validator implements ValidatorConstraintInterface {
116126
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/explicit-function-return-type, @typescript-eslint/no-unused-vars
@@ -167,7 +177,7 @@ export class EmptyStringParamPipe implements PipeTransform {
167177
private constructor(paramName: string) {
168178
this.paramName = paramName;
169179
}
170-
180+
171181
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/explicit-function-return-type
172182
transform(value: string) {
173183
const trimmedValue = value.trim();
@@ -194,7 +204,6 @@ export class EmptyStringParamPipe implements PipeTransform {
194204
// });
195205
// };
196206

197-
198207
export function validateSchemaPayload(schemaPayload: ISchemaFields, schemaType: string): void {
199208
const errors: string[] = [];
200209

@@ -314,21 +323,19 @@ export class AgentSpinupValidator {
314323
public static validate(agentSpinupDto): void {
315324
this.validateWalletName(agentSpinupDto.walletName);
316325
}
317-
318326
}
319327

320328
export const validateEmail = (email: string): boolean => {
321329
const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
322330
return emailRegex.test(email);
323331
};
324332

325-
326333
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/explicit-function-return-type
327334
export const createOobJsonldIssuancePayload = (JsonldCredentialDetails: IJsonldCredential, prettyVc: IPrettyVc) => {
328-
const {credentialData, orgDid, orgId, schemaLedgerId, schemaName, isReuseConnection} = JsonldCredentialDetails;
329-
const credentialSubject = { };
335+
const { credentialData, orgDid, orgId, schemaLedgerId, schemaName, isReuseConnection } = JsonldCredentialDetails;
336+
const credentialSubject = {};
330337

331-
const proofType = (orgDid?.includes(DidMethod.POLYGON)) ? ProofType.POLYGON_PROOFTYPE : ProofType.NO_LEDGER_PROOFTYPE;
338+
const proofType = orgDid?.includes(DidMethod.POLYGON) ? ProofType.POLYGON_PROOFTYPE : ProofType.NO_LEDGER_PROOFTYPE;
332339

333340
for (const key in credentialData) {
334341
if (credentialData.hasOwnProperty(key) && TemplateIdentifier.EMAIL_COLUMN !== key) {
@@ -339,41 +346,39 @@ export const createOobJsonldIssuancePayload = (JsonldCredentialDetails: IJsonldC
339346
return {
340347
credentialOffer: [
341348
{
342-
'emailId': `${credentialData.email_identifier}`,
343-
'credential': {
349+
emailId: `${credentialData.email_identifier}`,
350+
credential: {
344351
'@context': ['https://www.w3.org/2018/credentials/v1', `${schemaLedgerId}`],
345-
'type': [
346-
'VerifiableCredential',
347-
`${schemaName}`
348-
],
349-
'issuer': {
350-
'id': `${orgDid}`
352+
type: ['VerifiableCredential', `${schemaName}`],
353+
issuer: {
354+
id: `${orgDid}`
351355
},
352-
'issuanceDate': new Date().toISOString(),
356+
issuanceDate: new Date().toISOString(),
353357
credentialSubject,
354358
prettyVc
355359
},
356-
'options': {
360+
options: {
357361
proofType,
358-
'proofPurpose': 'assertionMethod'
362+
proofPurpose: 'assertionMethod'
359363
}
360364
}
361365
],
362-
'comment': 'string',
363-
'protocolVersion': 'v2',
364-
'credentialType': 'jsonld',
366+
comment: 'string',
367+
protocolVersion: 'v2',
368+
credentialType: 'jsonld',
365369
orgId,
366370
isReuseConnection
367371
};
368372
};
369373

370-
371374
@ValidatorConstraint({ name: 'isHostPortOrDomain', async: false })
372375
export class IsHostPortOrDomainConstraint implements ValidatorConstraintInterface {
373376
validate(value: string): boolean {
374377
// Regular expression for validating URL with host:port or domain
375-
const hostPortRegex = /^(http:\/\/|https:\/\/)?(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)):(?:\d{1,5})(\/[^\s]*)?$/;
376-
const domainRegex = /^(http:\/\/|https:\/\/)?(?:localhost|(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})(:\d{1,5})?(\/[^\s]*)?$/;
378+
const hostPortRegex =
379+
/^(http:\/\/|https:\/\/)?(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)):(?:\d{1,5})(\/[^\s]*)?$/;
380+
const domainRegex =
381+
/^(http:\/\/|https:\/\/)?(?:localhost|(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})(:\d{1,5})?(\/[^\s]*)?$/;
377382

378383
return hostPortRegex.test(value) || domainRegex.test(value);
379384
}
@@ -396,10 +401,9 @@ export function IsHostPortOrDomain(validationOptions?: ValidationOptions) {
396401
}
397402

398403
export function checkDidLedgerAndNetwork(schemaType: string, did: string): boolean {
399-
400404
const cleanSchemaType = schemaType.trim().toLowerCase();
401405
const cleanDid = did.trim().toLowerCase();
402-
406+
403407
if (JSONSchemaType.POLYGON_W3C === cleanSchemaType) {
404408
return cleanDid.includes(JSONSchemaType.POLYGON_W3C);
405409
}

libs/common/src/common.service.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@ import * as CryptoJS from 'crypto-js';
99
import { BadRequestException, HttpException, HttpStatus, Injectable, Logger, NotFoundException } from '@nestjs/common';
1010

1111
import { CommonConstants } from './common.constant';
12-
import { HttpService } from '@nestjs/axios/dist';
12+
import { HttpService } from '@nestjs/axios';
1313
import * as dotenv from 'dotenv';
1414
import { ResponseMessages } from './response-messages';
1515
import { IFormattedResponse, IOptionalParams } from './interfaces/interface';
16-
import { OrgAgentType } from '@credebl/enum/enum';
16+
import { OrgAgentType } from '../../enum/src/enum';
1717
import { RpcException } from '@nestjs/microservices';
1818
dotenv.config();
1919

@@ -236,7 +236,6 @@ export class CommonService {
236236
}
237237

238238
/**
239-
*
240239
* This function is used to handle errors in apps with RpcException
241240
*/
242241
handleError(error): Promise<void> {

libs/common/src/interfaces/cloud-wallet.interface.ts

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,35 @@
1-
import { CloudWalletType } from '@credebl/enum/enum';
1+
import { CloudWalletType } from '../../../enum/src/enum';
22
import { $Enums } from '@prisma/client';
33

44
export class ICreateCloudWallet {
5-
label: string;
6-
connectionImageUrl?: string;
7-
email?: string;
8-
userId?: string;
9-
}
5+
label: string;
6+
connectionImageUrl?: string;
7+
email?: string;
8+
userId?: string;
9+
}
1010

1111
export interface ICloudWalletDetails {
12-
label: string;
13-
tenantId: string;
14-
email?: string;
15-
type: CloudWalletType;
16-
createdBy: string;
17-
lastChangedBy: string;
18-
userId: string;
19-
agentEndpoint?: string;
20-
agentApiKey?: string;
21-
key?: string;
22-
connectionImageUrl?: string;
23-
}
12+
label: string;
13+
tenantId: string;
14+
email?: string;
15+
type: CloudWalletType;
16+
createdBy: string;
17+
lastChangedBy: string;
18+
userId: string;
19+
agentEndpoint?: string;
20+
agentApiKey?: string;
21+
key?: string;
22+
connectionImageUrl?: string;
23+
}
2424

2525
export interface IStoredWalletDetails {
26-
email: string,
27-
connectionImageUrl: string,
28-
createDateTime: Date,
29-
id: string,
30-
tenantId: string,
31-
label: string,
32-
lastChangedDateTime: Date
26+
email: string;
27+
connectionImageUrl: string;
28+
createDateTime: Date;
29+
id: string;
30+
tenantId: string;
31+
label: string;
32+
lastChangedDateTime: Date;
3333
}
3434

3535
export interface IReceiveInvitation {
@@ -96,8 +96,8 @@ export interface IStoreWalletInfo {
9696
agentEndpoint: string;
9797
type: CloudWalletType;
9898
userId: string;
99-
createdBy: string;
100-
lastChangedBy: string
99+
createdBy: string;
100+
lastChangedBy: string;
101101
}
102102

103103
export interface IGetStoredWalletInfo {
@@ -328,5 +328,5 @@ export interface IBasicMessageDetails {
328328
userId?: string;
329329
email?: string;
330330
content: string;
331-
connectionId: string
331+
connectionId: string;
332332
}

0 commit comments

Comments
 (0)