AI Hints
Home›TypeScript Tutorial›Project: Final Run
TypeScript · Lesson 110 of 120

Project: Final Run

End to end.

⏱ 2 min read▶ Video at 1:27:04🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Time to run the whole library, end to end. Restock from the warehouse, take orders, react to events, cancel one, and report.

Project: Final Run
From the video: Project: Final Run
  • Restock
  • Orders and events
  • Cancel and report

Everything together

Listeners print each event. We restock from the warehouse. Then the CLI places orders, cancels one, and lists them. Finally, the status counts. Run it. Every part of the library works together, fully typed.

app.tstypescript
import { on } from "./events.js";
import { PRODUCTS, STOCK } from "./catalog.js";
import { warehouseStock } from "./warehouse.js";
import { run } from "./cli.js";
import { orders } from "./service.js";
import { countByStatus } from "./reports.js";

on("order.placed", o => console.log("  [event] placed", o.id));
on("order.cancelled", e => console.log("  [event] cancelled", e.id));

const counts = await Promise.all(PRODUCTS.map(p => warehouseStock(p.sku)));
PRODUCTS.forEach((p, i) => (STOCK[p.sku] = counts[i]));

const script = [["place", "Sam", "TRAIL-500:1"], ["place", "Priya", "LIGHTS:2"],
                ["place", "Leo", "HELMET-M:0"], ["cancel", "1043"], ["list"]];
for (const args of script) { console.log(">", args.join(" ")); console.log(run(args)); }
console.log(countByStatus(orders.all()));
Output
> place Sam TRAIL-500:1
  [event] placed 1042
placed 1042
> place Priya LIGHTS:2
  [event] placed 1043
placed 1043
> place Leo HELMET-M:0
error: qty must be positive
> cancel 1043
  [event] cancelled 1043
cancelled 1043
> list
{"id":1042,"customer":"Sam","status":"packing","total":849.5}
{"id":1043,"customer":"Priya","status":"cancelled","total":50}
{ packing: 1, shipped: 0, delivered: 0, cancelled: 1 }
Also uses types.ts
export type Status = "packing" | "shipped" | "delivered" | "cancelled";

export interface Product {
  sku: string;
  name: string;
  price: number;
}

export interface OrderLine {
  sku: string;
  qty: number;
}

export interface Order {
  id: number;
  customer: string;
  lines: OrderLine[];
  status: Status;
}
Also uses catalog.ts
import type { Product } from "./types.js";

export const PRODUCTS: Product[] = [
  { sku: "TRAIL-500", name: "Trail 500", price: 849.5 },
  { sku: "HELMET-M", name: "Helmet", price: 40 },
  { sku: "LIGHTS", name: "Lights", price: 25 },
];

export const STOCK: Record<string, number> = { "TRAIL-500": 2, "HELMET-M": 10, LIGHTS: 0 };

export function product(sku: string): Product | undefined {
  return PRODUCTS.find(p => p.sku === sku);
}
Also uses schema.ts
import { z } from "zod";

export const NewOrderSchema = z.object({
  customer: z.string().min(1, "customer is required"),
  lines: z.array(z.object({
    sku: z.string(),
    qty: z.number().int().positive("qty must be positive"),
  })).min(1, "an order needs at least one line"),
});

export type NewOrder = z.infer<typeof NewOrderSchema>;
Also uses store.ts
export class Repository<T extends { id: number }> {
  private items = new Map<number, T>();

  save(item: T): T {
    this.items.set(item.id, item);
    return item;
  }

  find(id: number): T | undefined {
    return this.items.get(id);
  }

  all(): T[] {
    return [...this.items.values()];
  }
}
Also uses result.ts
export type Result<T> = { ok: true; value: T } | { ok: false; error: string };

export const ok = <T>(value: T): Result<T> => ({ ok: true, value });
export const fail = <T = never>(error: string): Result<T> => ({ ok: false, error });
Also uses events.ts
import type { Order } from "./types.js";

type Events = {
  "order.placed": Order;
  "order.cancelled": { id: number; reason: string };
};
type Listener<K extends keyof Events> = (payload: Events[K]) => void;

const listeners: { [K in keyof Events]: Listener<K>[] } = { "order.placed": [], "order.cancelled": [] };

export function on<K extends keyof Events>(name: K, fn: Listener<K>) {
  listeners[name].push(fn);
}
export function emit<K extends keyof Events>(name: K, payload: Events[K]) {
  listeners[name].forEach(fn => fn(payload));
}
Also uses service.ts
import { NewOrderSchema } from "./schema.js";
import { Repository } from "./store.js";
import { STOCK, product } from "./catalog.js";
import { ok, fail, type Result } from "./result.js";
import { emit } from "./events.js";
import type { Order } from "./types.js";
export const orders = new Repository<Order>();
let nextId = 1042;
export function placeOrder(input: unknown): Result<Order> {
  const parsed = NewOrderSchema.safeParse(input);
  if (!parsed.success) return fail(parsed.error.issues[0].message);
  for (const { sku, qty } of parsed.data.lines) {
    if (!product(sku)) return fail(`unknown product ${sku}`);
    if ((STOCK[sku] ?? 0) < qty) return fail(`not enough stock for ${sku}`);
  }
  parsed.data.lines.forEach(({ sku, qty }) => (STOCK[sku] -= qty));
  const order = orders.save({ id: nextId++, ...parsed.data, status: "packing" });
  emit("order.placed", order); return ok(order);
}
Also uses cancel.ts
import { orders } from "./service.js";
import { ok, fail, type Result } from "./result.js";
import { emit } from "./events.js";
import type { Order } from "./types.js";

export function cancelOrder(id: number, reason: string): Result<Order> {
  const order = orders.find(id);
  if (!order) return fail(`order ${id} not found`);
  if (order.status !== "packing") return fail(`order ${id} is ${order.status}, too late to cancel`);
  const cancelled = orders.save({ ...order, status: "cancelled" });
  emit("order.cancelled", { id, reason });
  return ok(cancelled);
}
Also uses reports.ts
import type { Order, Status } from "./types.js";
import { product } from "./catalog.js";

export type OrderSummary = Pick<Order, "id" | "customer" | "status"> & { total: number };

export function summarise(order: Order): OrderSummary {
  const total = order.lines.reduce((sum, l) => sum + (product(l.sku)?.price ?? 0) * l.qty, 0);
  return { id: order.id, customer: order.customer, status: order.status, total };
}

export function countByStatus(orders: Order[]): Record<Status, number> {
  const counts: Record<Status, number> = { packing: 0, shipped: 0, delivered: 0, cancelled: 0 };
  for (const o of orders) counts[o.status]++;
  return counts;
}
Also uses warehouse.ts
const WAREHOUSE: Record<string, number> = { "TRAIL-500": 5, "HELMET-M": 40, LIGHTS: 12 };

export async function warehouseStock(sku: string): Promise<number> {
  await new Promise(resolve => setTimeout(resolve, 100));   // pretend network call
  return WAREHOUSE[sku] ?? 0;
}
Also uses cli.ts
import { placeOrder, orders } from "./service.js";
import { cancelOrder } from "./cancel.js";
import { summarise } from "./reports.js";

export function run(args: string[]): string {
  const [command, ...rest] = args;
  switch (command) {
    case "place": {
      const [customer, ...items] = rest;
      const lines = items.map(i => ({ sku: i.split(":")[0], qty: Number(i.split(":")[1]) }));
      const r = placeOrder({ customer, lines });
      return r.ok ? `placed ${r.value.id}` : `error: ${r.error}`;
    }
    case "cancel": { const r = cancelOrder(Number(rest[0]), "customer request");
      return r.ok ? `cancelled ${r.value.id}` : `error: ${r.error}`; }
    case "list": return orders.all().map(o => JSON.stringify(summarise(o))).join("\n");
    default: return "usage: place NAME SKU:QTY... | cancel ID | list";
  }
}

Summary

Validation, rules, events, async, reports, and a CLI, all working together. Next, a review.

Key takeaways
  • End to end
  • Fully typed
  • All parts together
Next up: Project Review — what we built