Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: batchCreateWallet & batchTransferWallet service and controller #492

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
39c80b4
feat: add batchCreateWallet service & controller
yunchipang Nov 8, 2024
1d5febd
test: batchCreateWallet test passed
yunchipang Nov 13, 2024
b1ff980
feat: use uuid as unique identifier
yunchipang Nov 19, 2024
aaa421c
feat: add BatchCreateWalletDto
yunchipang Nov 19, 2024
2ecf603
feat: move error handling from controller to service
yunchipang Nov 19, 2024
9ff3e6f
test: add batchTransferWallet tests to wallet.service.spec.ts
yunchipang Nov 19, 2024
d9e1845
test: add failure test cases to batchCreateWallet in wallet.service.s…
yunchipang Nov 19, 2024
b6d5586
test: add batchCreateWallet test suite in wallet.controller.spec.ts
yunchipang Nov 20, 2024
d9ef7e3
test: mock fs module in batchCreateWallet unit tests
yunchipang Nov 20, 2024
ebffa42
test: update wallet controller test
yunchipang Nov 20, 2024
5080e99
feat: add validations to DTOs
yunchipang Nov 20, 2024
528ae11
feat: add csv file filter util and test
yunchipang Nov 22, 2024
b6d1361
test: update batchTransferWallet test to take a csv input file
yunchipang Nov 22, 2024
44fadf4
test: update batchTransferWallet tests to match the pattern of batchC…
yunchipang Nov 22, 2024
3ac0069
feat: add CsvItemDto for validation
yunchipang Dec 4, 2024
d8bb927
feat: add validation pipe to batchWalletTransfer as well
yunchipang Dec 4, 2024
f328495
feat: batch-create-wallet endpoint protected by csv file check
yunchipang Dec 17, 2024
783f304
feat: batch-create-wallet endpoint success
yunchipang Dec 20, 2024
8a4b37c
feat: batch-transfer endpoint success
yunchipang Dec 23, 2024
5879088
test: fix npm tests
yunchipang Dec 23, 2024
250ee4a
feat: make batchCreateWallet and batchTransferWallet database transac…
yunchipang Jan 3, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ services:
environment:
- DATABASE_URL=postgresql://wallet_user:secret@db:5432/wallet_user
- NODE_ENV=development
- S3_BUCKET=aws-s3
- S3_REGION=aws-s3
ports:
- '3006:3006'
depends_on:
Expand Down
Empty file added eslint
Empty file.
2,007 changes: 1,370 additions & 637 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"db-migrate-ci": "cd database; ../node_modules/db-migrate/bin/db-migrate --env dev up"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.637.0",
"@aws-sdk/client-s3": "^3.85.0",
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.1.1",
"@nestjs/core": "^10.0.0",
Expand All @@ -49,6 +49,7 @@
"axios": "^1.7.5",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"csvtojson": "^2.0.10",
"db-migrate": "^0.11.14",
"db-migrate-pg": "^1.5.2",
"dotenv": "^16.4.5",
Expand Down Expand Up @@ -82,6 +83,7 @@
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"chai": "^4.5.0",
"commitlint": "^19.5.0",
"eslint": "^8.51.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
Expand Down
17 changes: 17 additions & 0 deletions src/common/interceptors/csvFileUpload.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import * as uuid from 'uuid';
import { csvFileFilter } from '../utils/csvFileFilter';

export const CsvFileUploadInterceptor = () =>
FileInterceptor('file', {
storage: diskStorage({
destination: './uploads',
filename: (req, file, callback) => {
const uniqueFilename = `${file.fieldname}-${uuid.v4()}-${file.originalname}`;
callback(null, uniqueFilename);
},
}),
fileFilter: csvFileFilter,
limits: { fileSize: 500000 }, // Set file size limit (500KB)
});
117 changes: 94 additions & 23 deletions src/common/repositories/base.repository.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {
Repository,
SelectQueryBuilder,
Brackets,
Repository,
DataSource,
WhereExpressionBuilder,
DeepPartial,
} from 'typeorm';
import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common';
Expand Down Expand Up @@ -36,33 +38,101 @@ export class BaseRepository<

protected whereBuilder(
filter: any,
builder: SelectQueryBuilder<Entity>,
): SelectQueryBuilder<Entity> {
builder: SelectQueryBuilder<Entity> | WhereExpressionBuilder,
): SelectQueryBuilder<Entity> | WhereExpressionBuilder {
if (filter.and) {
filter.and.forEach((condition: any) => {
builder.andWhere(
new SelectQueryBuilder<Entity>(this.manager.connection),
(subBuilder) => {
this.whereBuilder(condition, subBuilder);
return '';
},
new Brackets((qb) => {
this.whereBuilder(condition, qb);
}),
);
});
} else if (filter.or) {
filter.or.forEach((condition: any) => {
builder.orWhere(
new SelectQueryBuilder<Entity>(this.manager.connection),
(subBuilder) => {
this.whereBuilder(condition, subBuilder);
return '';
},
);
});
builder.andWhere(
new Brackets((qb) => {
filter.or.forEach((condition: any) => {
qb.orWhere(
new Brackets((subQb) => {
this.whereBuilder(condition, subQb);
}),
);
});
}),
);
} else {
Object.keys(filter).forEach((key) => {
builder.andWhere(`${builder.alias}.${key} = :${key}`, {
[key]: filter[key],
});
const value = filter[key];
if (typeof value === 'object' && value !== null) {
if (value.ilike) {
// Handle ILIKE operation
const relationPath = key.split('.');
if (relationPath.length > 1) {
// It's a relation, we need to join
if (builder instanceof SelectQueryBuilder) {
const relationAlias = relationPath.slice(0, -1).join('_');
const relationProperty = relationPath[relationPath.length - 1];
builder.leftJoinAndSelect(
`${builder.alias}.${relationPath[0]}`,
relationAlias,
);
builder.andWhere(
`${relationAlias}.${relationProperty} ILIKE :${key}`,
{
[key]: value.ilike,
},
);
}
} else {
builder.andWhere(
`${builder instanceof SelectQueryBuilder ? builder.alias + '.' : ''}${key} ILIKE :${key}`,
{
[key]: value.ilike,
},
);
}
} else {
// Handle other object conditions (e.g., greater than, less than, etc.)
Object.keys(value).forEach((operator) => {
const operatorValue = value[operator];
switch (operator) {
case 'gt':
builder.andWhere(
`${builder instanceof SelectQueryBuilder ? builder.alias + '.' : ''}${key} > :${key}_${operator}`,
{ [`${key}_${operator}`]: operatorValue },
);
break;
case 'gte':
builder.andWhere(
`${builder instanceof SelectQueryBuilder ? builder.alias + '.' : ''}${key} >= :${key}_${operator}`,
{ [`${key}_${operator}`]: operatorValue },
);
break;
case 'lt':
builder.andWhere(
`${builder instanceof SelectQueryBuilder ? builder.alias + '.' : ''}${key} < :${key}_${operator}`,
{ [`${key}_${operator}`]: operatorValue },
);
break;
case 'lte':
builder.andWhere(
`${builder instanceof SelectQueryBuilder ? builder.alias + '.' : ''}${key} <= :${key}_${operator}`,
{ [`${key}_${operator}`]: operatorValue },
);
break;
// Add more operators as needed
}
});
}
} else {
// Handle simple equality
builder.andWhere(
`${builder instanceof SelectQueryBuilder ? builder.alias + '.' : ''}${key} = :${key}`,
{
[key]: value,
},
);
}
});
}
return builder;
Expand Down Expand Up @@ -105,7 +175,6 @@ export class BaseRepository<
}

queryBuilder = queryBuilder.orderBy(column, order);

return await queryBuilder.getMany();
}

Expand Down Expand Up @@ -169,8 +238,10 @@ export class BaseRepository<
* Return ids created
*/
async batchCreate(objects: Partial<Entity>[]): Promise<string[]> {
// Log the batch of objects being inserted
this.logger.debug('Object batch:', objects);
// Log each object individually for inspection
objects.forEach((obj, index) => {
this.logger.debug(`Object ${index + 1}:`, obj);
});

// Insert the batch of objects and get the result
const result = await this.createQueryBuilder()
Expand Down
21 changes: 21 additions & 0 deletions src/common/utils/__tests__/csvFileFilter.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { csvFileFilter } from '../csvFileFilter';
import { BadRequestException } from '@nestjs/common';

describe('csvFileFilter', () => {
it('should accept a CSV file', () => {
const file = { mimetype: 'text/csv' } as Express.Multer.File;
const callback = jest.fn();
csvFileFilter(null, file, callback);
expect(callback).toHaveBeenCalledWith(null, true);
});

it('should reject a non-CSV file', () => {
const file = { mimetype: 'text/plain' } as Express.Multer.File;
const callback = jest.fn();
csvFileFilter(null, file, callback);
expect(callback).toHaveBeenCalledWith(
expect.any(BadRequestException),
false,
);
});
});
18 changes: 18 additions & 0 deletions src/common/utils/csvFileFilter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { BadRequestException } from '@nestjs/common';

export const csvFileFilter = (
req: any,
file: Express.Multer.File,
callback: (error: Error | null, acceptFile: boolean) => void,
) => {
if (
file.mimetype === 'text/csv' ||
file.mimetype === 'application/csv' ||
file.mimetype === 'application/vnd.ms-excel' ||
(file.originalname && file.originalname.toLowerCase().endsWith('.csv'))
) {
callback(null, true);
} else {
callback(new BadRequestException('Only CSV files are supported.'), false);
}
};
5 changes: 5 additions & 0 deletions src/modules/event/event-enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ export enum EVENT_TYPES {
transfer_completed = 'transfer_completed',
transfer_requested = 'transfer_requested',
transfer_request_cancelled_by_destination = 'transfer_request_cancelled_by_destination',
transfer_request_cancelled_by_source = 'transfer_request_cancelled_by_source',
transfer_request_cancelled_by_originator = 'transfer_request_cancelled_by_originator',
transfer_pending_cancelled_by_source = 'transfer_pending_cancelled_by_source',
transfer_pending_cancelled_by_destination = 'transfer_pending_cancelled_by_destination',
transfer_pending_cancelled_by_requestor = 'transfer_pending_cancelled_by_requestor',
transfer_failed = 'transfer_failed',

Expand All @@ -14,6 +18,7 @@ export enum EVENT_TYPES {
trust_request_granted = 'trust_request_granted',
trust_request_cancelled_by_target = 'trust_request_cancelled_by_target',
trust_request_cancelled_by_originator = 'trust_request_cancelled_by_originator',
trust_request_cancelled_by_actor = 'trust_request_cancelled_by_actor',

// WALLET_EVENTS
wallet_created = 'wallet_created',
Expand Down
7 changes: 4 additions & 3 deletions src/modules/token/token.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { TokenRepository } from './token.repository';
import { TokenService } from './token.service';
import { TransactionModule } from '../transaction/transaction.module';
import { Token } from './entity/token.entity';

@Module({
imports: [TypeOrmModule.forFeature([TokenRepository]), TransactionModule],
providers: [TokenService],
exports: [TokenService],
imports: [TypeOrmModule.forFeature([Token]), TransactionModule],
providers: [TokenRepository, TokenService],
exports: [TokenRepository, TokenService],
})
export class TokenModule {}
6 changes: 3 additions & 3 deletions src/modules/token/token.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export class TokenService {
{
transfer_pending: false,
transfer_pending_id: null,
wallet_id: transfer.destination_wallet_id,
wallet_id: transfer.destinationWalletId,
claim: claimBoolean,
},
tokens.map((token) => token.id),
Expand All @@ -84,8 +84,8 @@ export class TokenService {
tokens.map((token) => ({
token_id: token.id,
transfer_id: transfer.id,
source_wallet_id: transfer.source_wallet_id,
destination_wallet_id: transfer.destination_wallet_id,
source_wallet_id: transfer.sourceWalletId,
destination_wallet_id: transfer.destinationWalletId,
claim: claimBoolean,
})),
);
Expand Down
12 changes: 12 additions & 0 deletions src/modules/transaction/entity/transaction.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,30 @@ export class Transaction {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column({ type: 'uuid', nullable: false })
token_id: string;

@ManyToOne(() => Token)
@JoinColumn({ name: 'token_id' })
token: Token;

@Column({ type: 'uuid', nullable: false })
transfer_id: string;

@ManyToOne(() => Transfer)
@JoinColumn({ name: 'transfer_id' })
transfer: Transfer;

@Column({ type: 'uuid', nullable: false })
source_wallet_id: string;

@ManyToOne(() => Wallet)
@JoinColumn({ name: 'source_wallet_id' })
sourceWallet: Wallet;

@Column({ type: 'uuid', nullable: false })
destination_wallet_id: string;

@ManyToOne(() => Wallet)
@JoinColumn({ name: 'destination_wallet_id' })
destinationWallet: Wallet;
Expand Down
35 changes: 28 additions & 7 deletions src/modules/transfer/entity/transfer.entity.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,54 @@
import { Wallet } from '../../wallet/entity/wallet.entity';
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { TRANSFER_STATES } from '../transfer-enums';
import {
Column,
Entity,
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
} from 'typeorm';
import { TRANSFER_STATES, TRANSFER_TYPES } from '../transfer-enums';

@Entity({ name: 'transfer' })
export class Transfer {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column({ name: 'originator_wallet_id' })
originatorWalletId: string;

@ManyToOne(() => Wallet)
originator_wallet_id: string;
@JoinColumn({ name: 'originator_wallet_id' })
originatorWallet: Wallet;

@Column({ name: 'source_wallet_id' })
sourceWalletId: string;

@ManyToOne(() => Wallet)
source_wallet_id: string;
@JoinColumn({ name: 'source_wallet_id' })
sourceWallet: Wallet;

@Column({ name: 'destination_wallet_id' })
destinationWalletId: string;

@ManyToOne(() => Wallet)
destination_wallet_id: string;
@JoinColumn({ name: 'destination_wallet_id' })
destinationWallet: Wallet;

@Column({ type: 'enum', enum: TRANSFER_STATES })
state: TRANSFER_STATES;

@Column({ type: 'enum', enum: TRANSFER_TYPES })
type: TRANSFER_TYPES;

@Column('jsonb', { nullable: true })
parameters: any;

@Column({ default: false })
claim: boolean;

@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
createdAt: Date;
created_at: Date;

@Column({ type: 'timestamp', nullable: true })
closedAt: Date;
closed_at: Date;
}
Loading
Loading