parent
f65fbce4d6
commit
e18858fd60
3 changed files with 34 additions and 6 deletions
@ -0,0 +1,4 @@ |
||||
export interface AddBalanceResponse { |
||||
message: string; |
||||
balance: number; |
||||
} |
@ -1,15 +1,31 @@ |
||||
import { Injectable } from '@nestjs/common'; |
||||
import { InjectModel } from '@nestjs/sequelize'; |
||||
import { Wallet } from './entities/wallet.entity';
|
||||
import { Injectable } from "@nestjs/common"; |
||||
import { InjectModel } from "@nestjs/sequelize"; |
||||
import { Wallet } from "./entities/wallet.entity"; |
||||
import { HttpException, HttpStatus } from "@nestjs/common"; |
||||
import { AddBalanceResponse } from "./add-balance-response.interface"; |
||||
|
||||
@Injectable() |
||||
export class WalletService { |
||||
constructor( |
||||
@InjectModel(Wallet) private walletModel: typeof Wallet, |
||||
) {} |
||||
constructor(@InjectModel(Wallet) private walletModel: typeof Wallet) {} |
||||
|
||||
async getBalance(userId: number): Promise<number> { |
||||
const wallet = await this.walletModel.findOne({ where: { userId } }); |
||||
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…
Reference in new issue