Add functionality to add balance to user's wallet in wallet module

master
nicekid1 2 months ago
parent f65fbce4d6
commit e18858fd60
  1. 4
      src/wallet/add-balance-response.interface.ts
  2. 8
      src/wallet/wallet.controller.ts
  3. 28
      src/wallet/wallet.service.ts

@ -0,0 +1,4 @@
export interface AddBalanceResponse {
message: string;
balance: number;
}

@ -1,5 +1,6 @@
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common'; import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { WalletService } from './wallet.service'; import { WalletService } from './wallet.service';
import { AddBalanceResponse } from './add-balance-response.interface';
@Controller('wallet') @Controller('wallet')
export class WalletController { export class WalletController {
@ -8,4 +9,11 @@ export class WalletController {
async getBalance(@Param('userId') userId: number): Promise<number> { async getBalance(@Param('userId') userId: number): Promise<number> {
return this.walletService.getBalance(userId); return this.walletService.getBalance(userId);
} }
@Post(':userId/add')
async addBalance(
@Param('userId') userId: number,
@Body('amount') amount: number
): Promise<AddBalanceResponse> {
return this.walletService.addBalance(userId, amount);
}
} }

@ -1,15 +1,31 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from "@nestjs/common";
import { InjectModel } from '@nestjs/sequelize'; import { InjectModel } from "@nestjs/sequelize";
import { Wallet } from './entities/wallet.entity'; import { Wallet } from "./entities/wallet.entity";
import { HttpException, HttpStatus } from "@nestjs/common";
import { AddBalanceResponse } from "./add-balance-response.interface";
@Injectable() @Injectable()
export class WalletService { export class WalletService {
constructor( constructor(@InjectModel(Wallet) private walletModel: typeof Wallet) {}
@InjectModel(Wallet) private walletModel: typeof Wallet,
) {}
async getBalance(userId: number): Promise<number> { async getBalance(userId: number): Promise<number> {
const wallet = await this.walletModel.findOne({ where: { userId } }); const wallet = await this.walletModel.findOne({ where: { userId } });
return wallet ? wallet.balance : 0; return wallet ? wallet.balance : 0;
} }
async addBalance(userId: number, amount: number): Promise<AddBalanceResponse> {
try {
const wallet = await this.walletModel.findOne({ where: { userId } });
if (wallet) {
wallet.balance += Number(amount);
await wallet.save();
return { message: "Balance updated successfully.", balance: wallet.balance };
} else {
const newWallet = await this.walletModel.create({ userId, balance: amount });
return { message: "Wallet created and balance added successfully.", balance: newWallet.balance };
}
} catch (error) {
throw new HttpException("An error occurred while adding balance to the wallet.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
} }

Loading…
Cancel
Save