Repository Interfaces - spinningideas/resources GitHub Wiki

What is a Repository Interface?

A repository interface defines the contract between an application and its data-access layer. It abstracts the details of how data is stored or queried, exposing only the operations the application needs-such as create, read, update, and delete. Implementations of the interface can then be swapped without changing the business logic.


Examples

TypeScript

export interface IRepository<T, TKey = string> {
  findById(id: TKey): Promise<T | null>;
  findAll(): Promise<T[]>;
  findOne(filter: Partial<T>): Promise<T | null>;
  add(entity: T): Promise<T>;
  update(id: TKey, entity: Partial<T>): Promise<T | null>;
  delete(id: TKey): Promise<boolean>;
}

Examples

Python

from abc import ABC, abstractmethod
from typing import Generic, TypeVar, List, Optional

T = TypeVar('T')
K = TypeVar('K')

class IRepository(ABC, Generic[T, K]):
    @abstractmethod
    def find_by_id(self, id: K) -> Optional[T]: ...
    @abstractmethod
    def find_all(self) -> List[T]: ...
    @abstractmethod
    def add(self, entity: T) -> T: ...
    @abstractmethod
    def update(self, id: K, entity: T) -> Optional[T]: ...
    @abstractmethod
    def delete(self, id: K) -> bool: ...

Examples

Java

public interface IRepository<T, K> {
    T findById(K id);
    List<T> findAll();
    T save(T entity);
    T update(K id, T entity);
    boolean delete(K id);
}

Examples

Rust

pub trait Repository<T, K> {
    fn find_by_id(&self, id: K) -> Option<T>;
    fn find_all(&self) -> Vec<T>;
    fn add(&mut self, entity: T) -> T;
    fn update(&mut self, id: K, entity: T) -> Option<T>;
    fn delete(&mut self, id: K) -> bool;
}

Go

type Repository[T any, K comparable] interface {
    FindById(id K) (T, bool)
    FindAll() []T
    Add(entity T) T
    Update(id K, entity T) (T, bool)
    Delete(id K) bool
}

Examples

c#

https://github.com/threenine/Threenine.Data/tree/master/src

public interface IRepository<T> : IDisposable where T : class
{
        Task<T> FindOne(Expression<Func<T, bool>> predicate = null;

        Task<IPagedList<T>> FindManyPagedOrdered(Expression<Func<T, bool>> predicate = null,
            Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
            Func<IQueryable<T>, IIncludableQueryable<T, object>> include = null,
            int pageNumber = 1,
            int pageSize = 20,
            CancellationToken cancellationToken = default);

	IQueryable<T> FindManyQuery(string sql, params object[] parameters);
	
	IQueryable<T> Search(params object[] keyValues);
		
	void Add(T entity);
	void Add(params T[] entities);
	void Add(IEnumerable<T> entities);

	void Delete(T entity);
	void Delete(object id);
	void Delete(params T[] entities);
	void Delete(IEnumerable<T> entities);	
	
	void Update(T entity);
	void Update(params T[] entities);
	void Update(IEnumerable<T> entities);
}

Examples

Node.js

Examples

Elf

Examples

⚠️ **GitHub.com Fallback** ⚠️