@syeedalireza/reverse-auction-engine
v1.0.0
Published
Professional reverse auction package
Readme
@syeedalireza/reverse-auction-engine
A robust, predictable finite state machine and core engine for Reverse Auctions.
Architecture
graph TD
Client[Client Request] --> Engine[ReverseAuctionEngine]
Engine --> Validation{Validate Bid}
Validation -->|Invalid| Error[Throw Error]
Validation -->|Valid| Lock[Acquire Distributed Lock]
Lock --> Storage[IStorageAdapter]
Storage -->|Save| DB[(Database / Redis / Memory)]Features
- State Management: Predictable transitions between DRAFT, ACTIVE, and CLOSED states.
- Bid Validation: Automatically rejects invalid bids (e.g., bids higher than current lowest).
- Auto-Extension: Automatically extends the auction end time if a bid is placed near the end (configurable threshold).
- Storage Adapters: Pluggable storage layer (Memory, Redis, DB) with distributed locking to prevent race conditions.
- Custom Errors: Uses custom error classes (
AuctionClosedError,InvalidBidError) for better error handling.
Installation
npm install @syeedalireza/reverse-auction-engineUsage
import { ReverseAuctionEngine, MemoryStorageAdapter } from '@syeedalireza/reverse-auction-engine';
// You can inject your own Redis or DB adapter here
const storage = new MemoryStorageAdapter();
const engine = new ReverseAuctionEngine({
id: 'auction-123',
extensionTimeMs: 5 * 60 * 1000, // Extend by 5 minutes
extensionThresholdMs: 2 * 60 * 1000, // If bid is placed within last 2 minutes
storage
});
async function run() {
// Start the auction
const endTime = Date.now() + 60 * 60 * 1000; // 1 hour from now
await engine.start(endTime);
// Place a bid
await engine.placeBid({
id: 'bid-1',
bidderId: 'user-1',
amount: 100,
timestamp: Date.now(),
});
console.log(await engine.getLowestBid());
}API
ReverseAuctionEngine
Constructor
new ReverseAuctionEngine(config: AuctionConfig)
config.id: Unique identifier for the auction.config.extensionTimeMs: Time to extend the auction by (in milliseconds). Default: 5 minutes.config.extensionThresholdMs: Threshold before end time to trigger an extension (in milliseconds). Default: 2 minutes.
Methods
start(endTime: number): void: Starts the auction.close(): void: Manually closes the auction.placeBid(bid: Bid): void: Places a bid. ThrowsInvalidBidErrororAuctionClosedError.getState(): AuctionState: Returns current state (DRAFT,ACTIVE,CLOSED).getLowestBid(): Bid | null: Returns the current lowest bid.getEndTime(): number: Returns the current end time.getBids(): Bid[]: Returns all placed bids.
