()
| 207 | // ==================== In-memory store (tests) ==================== |
| 208 | |
| 209 | export function createMemoryEntityStore(): IEntityStore { |
| 210 | const byKey = new Map<string, Entity>() |
| 211 | const emitter = new EventEmitter() |
| 212 | emitter.setMaxListeners(50) |
| 213 | |
| 214 | async function upsert(input: EntityInput): Promise<Entity> { |
| 215 | validateInput(input) |
| 216 | const k = keyOf(input.name) |
| 217 | const existing = byKey.get(k) |
| 218 | const entity: Entity = { |
| 219 | name: input.name.trim(), |
| 220 | description: input.description.trim(), |
| 221 | type: input.type, |
| 222 | createdAt: existing?.createdAt ?? Date.now(), |
| 223 | } |
| 224 | byKey.set(k, entity) |
| 225 | emitter.emit('changed') |
| 226 | return entity |
| 227 | } |
| 228 | |
| 229 | async function list(): Promise<Entity[]> { |
| 230 | return [...byKey.values()].sort(byNewest) |
| 231 | } |
| 232 | |
| 233 | async function get(name: string): Promise<Entity | null> { |
| 234 | return byKey.get(keyOf(name)) ?? null |
| 235 | } |
| 236 | |
| 237 | async function search(query: string): Promise<Entity[]> { |
| 238 | const q = query.trim().toLowerCase() |
| 239 | const all = await list() |
| 240 | return q ? all.filter((e) => matches(e, q)) : all |
| 241 | } |
| 242 | |
| 243 | async function deleteEntity(name: string): Promise<boolean> { |
| 244 | const removed = byKey.delete(keyOf(name)) |
| 245 | if (removed) emitter.emit('changed') |
| 246 | return removed |
| 247 | } |
| 248 | |
| 249 | function onChanged(listener: () => void): () => void { |
| 250 | emitter.on('changed', listener) |
| 251 | return () => { |
| 252 | emitter.off('changed', listener) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | return { upsert, list, get, search, delete: deleteEntity, onChanged } |
| 257 | } |
no outgoing calls