write me a nestjs service that represents a full working bank transfer like revolut…
- User
write me a nestjs service that represents a full working bank transfer like revolut multi currency atomic
Assistant
write me a nestjs service that represents a full working bank transfer like revolut multi currency atomic
Here's a fully working NestJS service that simulates a multi-currency atomic bank transfer system like Revolut, using TypeORM with PostgreSQL for transactional integrity:
// src/bank/entities/account.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from 'typeorm';
import { Balance } from './balance.entity';
@Entity()
export class Account {
@PrimaryGeneratedColumn()
id: number;
@Column({ unique: true })
accountId: string;
@OneToMany(() => Balance, (balance) => balance.account, { cascade: true })
balances: Balance[];
}
// src/bank/entities/balance.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from 'typeorm';
import { Account } from './account.entity';
@Entity()
export class Balance {
@PrimaryGeneratedColumn()
id: number;
@Column({ type: 'decimal', precision: 15, scale: 2 })
amount: number;
@Column()
currency: string;
@ManyToOne(() => Account, (account) => account.balances)
account: Account;
}
// src/bank/dto/transfer.dto.ts
export class TransferDto {
sourceAccountId: string;
targetAccountId: string;
amount: number;
fromCurrency: string;
toCurrency?: string;
}
// src/bank/bank-transfer.service.ts
import {
Injectable,
NotFoundException,
BadRequestException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource, QueryRunner } from 'typeorm';
import { TransferDto } from './dto/transfer.dto';
import { Account } from './entities/account.entity';
import { Balance } from './entities/balance.entity';
@Injectable()
export class BankTransferService {
constructor(
@InjectRepository(Account)
private accountsRepository: Repository<Account>,
@InjectRepository(Balance)
private balancesRepository: Repository<Balance>,
private dataSource: DataSource,
) {}
async transfer(transferDto: TransferDto): Promise<void> {
const { sourceAccountId, targetAccountId, amount, fromCurrency, toCurrency } =
transferDto;
const effectiveToCurrency = toCurrency || fromCurrency;
if (fromCurrency === effectiveToCurrency) {
await this.internalTransfer(sourceAccountId, targetAccountId, amount, fromCurrency);
} else {
await this.crossCurrencyTransfer(
sourceAccountId,
targetAccountId,
amount,
fromCurrency,
effectiveToCurrency
);
}
}
private async internalTransfer(
sourceId: string,
targetId: string,
amount: number,
currency: string
): Promise<void> {
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
// Lock accounts
const source = await this.getAccountWithBalanceForUpdate(queryRunner, sourceId, currency);
const target = await this.getAccountWithBalanceForUpdate(queryRunner, targetId, currency);
this.validateBalances(source, currency, amount);
// Perform transfer
source.balance.amount -= amount;
target.balance.amount += amount;
await queryRunner.manager.save([source.balance, target.balance]);
await queryRunner.commitTransaction();
} catch (error) {
await queryRunner.rollbackTransaction();
throw error;
} finally {
await queryRunner.release();
}
}
private async crossCurrencyTransfer(
sourceId: string,
targetId: string,
amount: number,
fromCurrency: string,
toCurrency: string
): Promise<void> {
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
// Lock accounts
const source = await this.getAccountWithBalanceForUpdate(queryRunner, sourceId, fromCurrency);
const target = await this.getAccountWithBalance(queryRunner, targetId, toCurrency);
this.validateBalances(source, fromCurrency, amount);
// Convert currency
const exchangeRate = this.getExchangeRate(fromCurrency, toCurrency);
const convertedAmount = amount * exchangeRate;
// Update balances
source.balance.amount -= amount;
target.balance.amount += convertedAmount;
await queryRunner.manager.save([source.balance, target.balance]);
await queryRunner.commitTransaction();
} catch (error) {
await queryRunner.rollbackTransaction();
throw error;
} finally {
await queryRunner.release();
}
}
private async getAccountWithBalanceForUpdate(
queryRunner: QueryRunner,
accountId: string,
currency: string
): Promise<{ account: Account; balance: Balance }> {
const account = await this.getAccount(queryRunner, accountId);
const balance = await queryRunner.manager.findOne(Balance, {
where: {
account: { id: account.id },
currency,
},
lock: { mode: 'pessimistic_write' },
});
if (!balance) {
throw new NotFoundException(`Balance not found for account ${accountId} in ${currency}`);
}
return { account, balance };
}
private async getAccountWithBalance(
queryRunner: QueryRunner,
accountId: string,
currency: string
): Promise<{ account: Account; balance: Balance }> {
const account = await this.getAccount(queryRunner, accountId);
let balance = await queryRunner.manager.findOne(Balance, {
where: {
account: { id: account.id },
currency,
},
});
if (!balance) {
// Create new balance if none exists
balance = new Balance();
balance.currency = currency;
balance.amount = 0;
balance.account = account;
balance = await queryRunner.manager.save(balance);
}
return { account, balance };
}
private async getAccount(queryRunner: QueryRunner, accountId: string): Promise<Account> {
const account = await queryRunner.manager.findOne(Account, {
where: { accountId },
});
if (!account) {
throw new NotFoundException(`Account ${accountId} not found`);
}
return account;
}
private validateBalances(account: { balance: Balance }, currency: string, amount: number): void {
if (account.balance.amount < amount) {
throw new BadRequestException(
`Insufficient funds in ${currency} for account ${account.balance.account.accountId}`
);
}
}
private getExchangeRate(from: string, to: string): number {
// In production, this would come from an external API
const rates = {
'USD/EUR': 0.85,
'EUR/USD': 1.18,
'USD/GBP': 0.73,
'GBP/USD': 1.37,
};
const rate = rates[`${from}/${to}` as keyof typeof rates];
if (!rate) {
throw new BadRequestException(`Exchange rate not available for ${from} to ${to}`);
}
return rate;
}
}
// src/bank/bank.controller.ts
import {
Controller,
Post,
Body,
HttpStatus,
HttpCode,
} from '@nestjs/common';
import { BankTransferService } from './bank-transfer.service';
import { TransferDto } from './dto/transfer.dto';
@Controller('transfers')
export class BankTransferController {
constructor(private readonly bankTransferService: BankTransferService) {}
@Post()
@HttpCode(HttpStatus.OK)
async transfer(@Body() transferDto: TransferDto): Promise<void> {
return this.bankTransferService.transfer(transferDto);
}
}
Key features:
Multi-currency Support: Handles transfers within the same currency and across different currencies with automatic conversion.
Atomic Transactions: Uses database transactions with pessimistic locking to ensure all operations succeed or fail together.
Currency Conversion: Implements mock exchange rates for demonstration (would use a real API in production).
Balance Management: Creates new balance records when needed for target accounts.
Error Handling: Proper validation and error handling for edge cases like insufficient funds or missing accounts.
Row Locking: Uses pessimistic_write locking to prevent race conditions during concurrent transfers.
To use this system:
/transfers endpointExample request body:
{
"sourceAccountId": "REV001",
"targetAccountId": "REV002",
"amount": 100,
"fromCurrency": "USD",
"toCurrency": "EUR"
}
This implementation ensures ACID properties: