示例工程 32-capstone-quality-gates
32-capstone-quality-gates/03-event-bus-form/src/main.ts
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
export interface AppEvents {
added: { id: number; title: string };
removed: { id: number };
}
export type Handler<T> = (payload: T) => void;
export interface Bus<E extends object> {
on<K extends keyof E>(name: K, handler: Handler<E[K]>): () => void;
emit<K extends keyof E>(name: K, payload: E[K]): void;
}
export function createBus<E extends object>(): Bus<E> {
// 内部用 unknown 存异构处理器,边界处再做一次收窄
const handlers = new Map<string, Set<(payload: unknown) => void>>();
return {
on(name, handler) {
const key = String(name);
const set = handlers.get(key) ?? new Set<(payload: unknown) => void>();
const wrapped = handler as (payload: unknown) => void;
set.add(wrapped);
handlers.set(key, set);
return () => {
set.delete(wrapped);
};
},
emit(name, payload) {
for (const handler of handlers.get(String(name)) ?? []) {
handler(payload);
}
},
};
}
export type Validation =
| { ok: true; value: { title: string } }
| { ok: false; errors: string[] };
export function validateTodo(input: { title: string }): Validation {
const title = input.title.trim();
const errors: string[] = [];
if (title.length === 0) errors.push('title is required');
if (title.length > 20) errors.push('title is too long');
return errors.length === 0 ? { ok: true, value: { title } } : { ok: false, errors };
}
export function run(log: (msg: string) => void = console.log): string[] {
const bus = createBus<AppEvents>();
const seen: string[] = [];
bus.on('added', (payload) => seen.push(`added:${payload.id}:${payload.title}`));
bus.on('removed', (payload) => seen.push(`removed:${payload.id}`));
const first = validateTodo({ title: ' ' });
const second = validateTodo({ title: ' write ' });
if (second.ok) bus.emit('added', { id: 1, title: second.value.title });
bus.emit('removed', { id: 1 });
const lines = [
first.ok ? 'valid' : `invalid:${first.errors.join(',')}`,
...seen,
];
for (const line of lines) {
log(line);
}
return lines;
}