Generic Repository Interface
Define a repository contract parameterised by entity and id type, so different stores share one shape without duplicating method signatures.
Code
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);
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.