You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

47 lines
1.6 KiB

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) {}
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 += 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);
}
}
async processPayment(userId: number, amount: number): Promise<string> {
const wallet = await this.walletModel.findOne({ where: { userId } });
if (!wallet) {
throw new Error("Wallet not found");
}
if (wallet.balance < amount) {
throw new Error("Insufficient funds");
}
wallet.balance -= amount;
await wallet.save();
return "Payment processed successfully";
}
}