Compare commits
2 Commits
021e22fcc9
...
e18858fd60
Author | SHA1 | Date |
---|---|---|
|
e18858fd60 | 4 months ago |
|
f65fbce4d6 | 4 months ago |
4 changed files with 46 additions and 4 deletions
@ -0,0 +1,4 @@ |
||||
export interface AddBalanceResponse { |
||||
message: string; |
||||
balance: number; |
||||
} |
@ -1,8 +1,19 @@ |
||||
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common'; |
||||
import { WalletService } from './wallet.service'; |
||||
import { AddBalanceResponse } from './add-balance-response.interface'; |
||||
|
||||
@Controller('wallet') |
||||
export class WalletController { |
||||
constructor(private readonly walletService: WalletService) {} |
||||
|
||||
@Get(':userId') |
||||
async getBalance(@Param('userId') userId: number): Promise<number> { |
||||
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,7 +1,31 @@ |
||||
import { Injectable } from '@nestjs/common'; |
||||
|
||||
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(){} |
||||
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