TypeScript · Lesson 101 of 120
Project: Services
Business rules.
Now the heart of the library. Placing an order validates the input, checks every product exists, checks stock, then saves the order. Any problem returns a clear error.

- Validate
- Check products and stock
- Save
service.ts
Place order takes unknown input, and returns a result. First the schema checks it. Then each line is checked against the catalogue and the stock. If all is well, stock goes down, and the order is saved as packing. Finally an event is sent.
service.tstypescript
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);
}Placing orders
We place a good order, one for a product that's sold out, and one for a product that doesn't exist. Run it. One order is placed, and the others explain what went wrong.
app.tstypescript
import { placeOrder } from "./service.js";
const attempts: unknown[] = [
{ customer: "Sam", lines: [{ sku: "HELMET-M", qty: 2 }, { sku: "TRAIL-500", qty: 1 }] },
{ customer: "Priya", lines: [{ sku: "LIGHTS", qty: 1 }] },
{ customer: "Leo", lines: [{ sku: "UNICYCLE", qty: 1 }] },
];
for (const a of attempts) {
const r = placeOrder(a);
console.log(r.ok ? `placed order ${r.value.id}` : `failed: ${r.error}`);
}Output
placed order 1042 failed: not enough stock for LIGHTS failed: unknown product UNICYCLE
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
The service validates, checks stock, saves, and returns a result. Next, errors and cancelling.
Key takeaways- placeOrder(input)
- Stock checks
- Result<Order>
Next up: Project: Errors — Result types