|
| 1 | +import type { BidInfo, CreateBidInfo } from '@shared/bids.ts'; |
| 2 | +import { Bid, type BidDataType } from '../db/models/bid.ts'; |
| 3 | +import AuctionsService from './auctions.ts'; |
| 4 | + |
| 5 | +class BidsService { |
| 6 | + // Get all the bids that have been made on a given auction. |
| 7 | + static async getAuctionBids(auctionId: string): Promise<BidInfo[]> { |
| 8 | + const bids = await Bid.find({ auctionId }); |
| 9 | + return bids.map((b) => this.parseBidInfo(b._id.toString(), b)); |
| 10 | + } |
| 11 | + |
| 12 | + // Make a new bid on an auction. |
| 13 | + static async createBid(bidInfo: CreateBidInfo): Promise<BidInfo> { |
| 14 | + const auction = await AuctionsService.getAuctionById(bidInfo.auctionId); |
| 15 | + |
| 16 | + // Make sure the bid is at least as high as the minimum bid. |
| 17 | + // We can make this preliminary check before going through all of the other bids |
| 18 | + // for a slight performance boost. |
| 19 | + if (bidInfo.amount < auction.minimumBid) { |
| 20 | + throw new Error('bid amount must be at least the minimum bid'); |
| 21 | + } |
| 22 | + // If the bid as at least as high as the minimum bid, then make sure it is higher |
| 23 | + // than all other bids that have been made. |
| 24 | + const currHighBid = await this.getCurrentHighestBid(bidInfo.auctionId); |
| 25 | + if (currHighBid && currHighBid.amount >= bidInfo.amount) { |
| 26 | + throw new Error('bid amount must be higher than the previous bid'); |
| 27 | + } |
| 28 | + |
| 29 | + // If the bid amount is valid, then create the new bid. |
| 30 | + const bid = new Bid({ |
| 31 | + userId: bidInfo.userId, |
| 32 | + amount: bidInfo.amount, |
| 33 | + auctionId: bidInfo.auctionId, |
| 34 | + }); |
| 35 | + await bid.save(); |
| 36 | + return this.parseBidInfo(bid._id.toString(), bid); |
| 37 | + } |
| 38 | + |
| 39 | + // Figure out what the current highest bid is on the given auction. |
| 40 | + private static async getCurrentHighestBid( |
| 41 | + auctionId: string, |
| 42 | + ): Promise<BidInfo | undefined> { |
| 43 | + const bids = await this.getAuctionBids(auctionId); |
| 44 | + if (bids.length === 0) return undefined; |
| 45 | + |
| 46 | + let maxBid = bids[0]; |
| 47 | + for (let i = 1; i < bids.length; i++) { |
| 48 | + if (bids[i].amount > maxBid.amount) { |
| 49 | + maxBid = bids[i]; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return maxBid; |
| 54 | + } |
| 55 | + |
| 56 | + // This function is used for taking an auction DB document and converting it to |
| 57 | + // a usable interface. |
| 58 | + private static parseBidInfo(bidId: string, bid: BidDataType): BidInfo { |
| 59 | + return { |
| 60 | + id: bidId, |
| 61 | + userId: bid.userId.toString(), |
| 62 | + amount: bid.amount, |
| 63 | + auctionId: bid.auctionId.toString(), |
| 64 | + createdDate: bid.createdAt, |
| 65 | + }; |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +export default BidsService; |
0 commit comments