Compare commits

..

2 Commits

  1. 4
      src/wallet/add-balance-response.interface.ts
  2. 13
      src/wallet/wallet.controller.ts
  3. 3
      src/wallet/wallet.module.ts
  4. 30
      src/wallet/wallet.service.ts

@ -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,8 +1,11 @@
import { Module } from '@nestjs/common';
import { WalletService } from './wallet.service';
import { WalletController } from './wallet.controller';
import { Wallet } from './entities/wallet.entity';
import { SequelizeModule } from '@nestjs/sequelize';
@Module({
imports: [SequelizeModule.forFeature([Wallet])],
controllers: [WalletController],
providers: [WalletService],
})

@ -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…
Cancel
Save