TypeScript · Lesson 100 of 120
Project: The Store
A generic repository.
Our orders need somewhere to live. A generic repository can store anything with a numeric ID. Today it holds orders. Tomorrow it could hold customers.

- Somewhere to live
- Anything with an id
- Reusable
store.ts
Repository of T requires an ID. Items live in a map. Save stores an item, and returns it. Find might return undefined. All returns every item, as a list.
store.tstypescript
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()];
}
}Using the store
We make a repository of orders, save one, and find it again. Run it. Find returns a fully typed order, so its status is available.
app.tstypescript
import { Repository } from "./store.js";
import type { Order } from "./types.js";
const repo = new Repository<Order>();
repo.save({ id: 1042, customer: "Sam", lines: [{ sku: "LIGHTS", qty: 1 }], status: "packing" });
console.log(repo.find(1042)?.status, "|", repo.find(9999), "|", repo.all().length, "order");Output
packing | undefined | 1 order
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
A generic repository stores any type with an ID. Next, the business rules.
Key takeaways- Repository<T>
- save, find, all
- Typed results
Next up: Project: Services — business rules