BaseRepository - Christin-paige/BuiltInPublic GitHub Wiki

The BaseRepository class is an abstract base class that provides a standardized way to interact with Supabase databases using the repository pattern. It offers common database operations with built-in support for filtering, pagination, search, and ordering.

Generic Type Parameters

  • TDto - The Data Transfer Object type representing the raw database row
  • TEntity - The entity type that the DTO is transformed into
  • TClient - The Supabase client type: SupabaseAnonClient for most queries, SupabaseServiceClient to bypass RLS (defaults to AnySupabaseClient)

Properties

protected supabase: TClient

The Supabase client instance used for database operations.

Constructor

constructor(supabase: TClient)

Initializes the repository with a Supabase client instance.

Parameters:

  • supabase - The Supabase client to use for database operations

Abstract Methods

These methods must be implemented by concrete repository classes:

abstract getRawBaseQuery(count: boolean): any

Returns the base query for the repository. This is where you define your table selection and any base joins.

Parameters:

  • count - Whether the query should return a count

abstract transformDTO(row: TDto): TEntity

Transforms a raw database row (DTO) into the desired entity format.

Parameters:

  • row - The raw database row to transform

Returns: The transformed entity

Public Methods

getBaseQuery(count?: boolean): FilterBuilder

Returns the base query wrapped as a FilterBuilder for chaining operations.

Parameters:

  • count - Optional boolean to indicate if count should be included (defaults to false)

Returns: A FilterBuilder instance

validateDTO(data: any): boolean

Validates whether the provided data satisfies the DTO type constraints.

Parameters:

  • data - The data to validate

Returns: Boolean indicating if the data is valid

async findAll(options: GetRepositoryOptions = {})

The main query method that combines filtering, searching, ordering, and pagination.

Parameters:

  • options - Configuration object with the following optional properties:
    • filters - Record of key-value pairs for filtering
    • search - Search term
    • searchColumn - Column to search in (supports foreign table syntax: "table.column")
    • orderBy - Column to order by
    • ascending - Sort direction (defaults to true)
    • page - Page number for pagination (starts at 1)
    • limit - Number of records per page (defaults to 10)
    • count - Whether to include count in the result

Returns: A query builder with all specified options applied

Protected Methods

protected safeTransformDTO(data: any): TEntity

Safely transforms a DTO with validation, throwing an error if the data is invalid.

Parameters:

  • data - The data to validate and transform

Returns: The transformed entity

Throws: Error if the DTO validation fails

applyPagination<T extends FilterBuilder>(query: T, page: number = 1, limit: number = 10): T

Applies pagination to a query using offset and limit.

Parameters:

  • query - The query builder to modify
  • page - Page number (defaults to 1)
  • limit - Records per page (defaults to 10)

Returns: The modified query builder

applyFilters<T extends FilterBuilder>(query: T, filters: Record<string, any>): T

Applies various types of filters to a query:

  • String values containing % are treated as LIKE queries
  • Array values are treated as IN queries
  • String values starting with ! are treated as NOT EQUAL queries
  • All other values are treated as equality filters

Parameters:

  • query - The query builder to modify
  • filters - Object containing filter key-value pairs

Returns: The modified query builder

applyOrdering<T extends FilterBuilder>(query: T, orderBy: string, ascending: boolean = true): T

Applies ordering to a query.

Parameters:

  • query - The query builder to modify
  • orderBy - Column name to order by
  • ascending - Sort direction (defaults to true)

Returns: The modified query builder

applySearch<T extends FilterBuilder>(query: T, searchTerm: string, column: string): T

Applies text search using case-insensitive LIKE matching. Supports searching in foreign tables using dot notation.

Parameters:

  • query - The query builder to modify
  • searchTerm - The text to search for
  • column - Column to search in (use "table.column" for foreign table columns)

Returns: The modified query builder

Interfaces

GetRepositoryOptions

Configuration interface for the findAll method:

export interface GetRepositoryOptions {
  filters?: Record<string, any>;
  search?: string;
  searchColumn?: string;
  orderBy?: string;
  ascending?: boolean;
  page?: number;
  limit?: number;
  count?: boolean;
}

Usage Example

To use this base repository, extend it and implement the abstract methods:

class UserRepository extends BaseRepository<UserDTO, User> {
  getRawBaseQuery(count: boolean) {
    return this.supabase
      .from('users')
      .select(count ? '*' : 'id, name, email, created_at');
  }

  transformDTO(row: UserDTO): User {
    return {
      id: row.id,
      name: row.name,
      email: row.email,
      createdAt: new Date(row.created_at)
    };
  }
}

// Usage
// This operation would return all active users with the name 'john'
const users = await userRepo.findAll({
  filters: { active: true },
  search: 'john',
  searchColumn: 'name'
});s