Generic Repository Interface

Define a repository contract parameterised by entity and id type, so different stores share one shape without duplicating method signatures.

TypescriptData Integrity

Code

typescriptsnippet
31 lines
export interface Entity {
  id: string;
}

export interface Repository<T extends Entity, Id = string> {
  findById(id: Id): Promise<T | null>;
  findAll(): Promise<T[]>;
  save(entity: T): Promise<T>;
  delete(id: Id): Promise<boolean>;
}

export class InMemoryRepository<T extends Entity> implements Repository<T> {
  private store = new Map<string, T>();

  async findById(id: string): Promise<T | null> {
    return this.store.get(id) ?? null;
  }

  async findAll(): Promise<T[]> {
    return [...this.store.values()];
  }

  async save(entity: T): Promise<T> {
    this.store.set(entity.id, entity);
    return entity;
  }

  async delete(id: string): Promise<boolean> {
    return this.store.delete(id);
  }
}

What the code does

Generic Repository Interface is built around the class InMemoryRepository.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Returns a newly built value, leaving the inputs as they were.

Applying it

InMemoryRepository is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

return this.store.get(id) ?? null;
async delete(id: string): Promise<boolean> {
return this.store.delete(id);
}
private store = new Map<string, T>();

Interactive Tools for This Topic

FAQ

Does `InMemoryRepository` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared.