7
← Back to Pattern Arsenal
behavioral

Command

must know

Stage 1: Problem

The Problem

You are building an admin dashboard for an e-commerce platform. Admins can perform operations like: refund an order, ban a user, adjust inventory, apply a coupon, and update product prices.

Your PM asks for three things:

  1. Undo — admins make mistakes. Every action must be reversible for the last 20 actions.
  2. Audit log — every action must be logged with who did it, when, what changed, and the ability to replay it.
  3. Queuing — some actions are expensive (refunds hit Stripe API, inventory syncs across warehouses). These should be queued and retried on failure.

Right now your code looks like this:

typescript
1class AdminController {
2 async refundOrder(orderId: string, adminId: string) {
3 const order = await this.orderRepo.findOne(orderId);
4 const refund = await this.stripe.refunds.create({ charge: order.chargeId });
5 order.status = 'refunded';
6 await this.orderRepo.save(order);
7 console.log(`Admin ${adminId} refunded order ${orderId}`);
8 }
9
10 async banUser(userId: string, adminId: string) {
11 const user = await this.userRepo.findOne(userId);
12 user.banned = true;
13 await this.userRepo.save(user);
14 console.log(`Admin ${adminId} banned user ${userId}`);
15 }
16
17 async adjustInventory(productId: string, delta: number, adminId: string) {
18 const product = await this.productRepo.findOne(productId);
19 product.stock += delta;
20 await this.productRepo.save(product);
21 console.log(`Admin ${adminId} adjusted inventory for ${productId} by ${delta}`);
22 }
23}

Think about it: How would you add undo, audit logging, and queuing to this code? How many places do you need to change when you add a new admin action?


Confused With a Similar Pattern?

1 / 10 — Problem