gormet

package module
v0.0.0-...-a53cc14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2023 License: Apache-2.0 Imports: 3 Imported by: 0

README

GORMET

A Gorm Gourmet repository pattern implementation

The main idea behind this project is to create an implementation of the Repository design pattern for golang.

It introduces a layer over the fantastic ORM library for Golang - GORM, to facilitate it use and reduce the amount of code used to perform mainly paged searches in the database

Logical Organization

This project is logically structured, containing as the center of everything the Repository that provides 5 (five) different types of functions listed below:

  • Get Functions: Set of functions that aim to obtain one and only one instance of an object;
  • Write Functions: Set of functions focused on saving or changing objects in the database;
  • Delete Functions: Set of functions to delete an object from the database, either physically or logically, depending on the configuration used;
  • Find Functions: Conglomerate of functions to perform search in the database and return a list of GORM objects
  • Pageable Functions: Similar to the find functions, this set of functions has the ability to make requests against the database and obtain a paging object, which can be navigated to obtain other pages.

Abaixo está impresso um diagrama de mapa mental que descreve o grupo descrito acima e identifica cada uma de suas funções.

mindmap
  root)Repository(
    (Get Functions)
      Get
      GetById
      GetLatest
    (Write Functions)
      Create
      Update
    (Delete Functions)
      Delete
      DeleteById
    (Find Functions)
      Find
      FindAll
    (Pageable Functions)
      Find
      FindAll

Examples

Documentation

Overview

Package gormet provides a set of utility functions for performing common database operations using GORM.

Usage: To use this package, create a GORM repository for your entity, and embed the Repository struct into it. Then, you can call the various utility functions provided by this package to perform operations such as Get, GetById, Search, and SearchAll.

Example:

type UserRepository struct {
	gormet.Repository[User]
}

func NewUserRepository(db *gorm.DB) (*UserRepository, error) {
	repo, err := gormet.New[User](db)
	if err != nil {
		return nil, err
	}

	return &UserRepository{
		Repository: repo,
	}, nil
}

// Now you can use the utility functions like Get, GetById, Search, and SearchAll on UserRepository.

import (
	"github.com/example/gormet"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Username string
	Email    string
}

userRepo, err := NewUserRepository(db)
if err != nil {
	// Handle error
}

// Retrieve a user by ID
userByID, err := userRepo.GetById(1)
if err != nil {
	// Handle error
}

// Search for users based on a filter
users, err := userRepo.Search(1, "username = ?", "john_doe")
if err != nil {
	// Handle error
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Pagination

type Pagination[T any] struct {
	Response Response[T] `json:"response"`
	// contains filtered or unexported fields
}

Pagination contains the response with actual content and additional data for paginated searches.

type Repository

type Repository[T any] struct {
	PageSize uint // Define if the size of page
	// contains filtered or unexported fields
}

Repository is a generic repository type that provides CRUD operations for a given model that is represented by a GORM model.

func New

func New[T any](db *gorm.DB) (*Repository[T], error)

New creates and returns a new instance of Repository for a specific model type T, with the provided database connection and optional configuration settings. It automatically determines the primary key field for the model type T.

Usage: repo, err := New[YourModelType](db, nil)

if err != nil {
    // Handle error
}

Parameters:

  • db: A *gorm.DB instance representing the database connection.

Returns: - A pointer to a newly created Repository for type T if successful. - An error if there is a failure in determining the primary key or other initializations.

func (*Repository[T]) Create

func (r *Repository[T]) Create(entity *T) error

Create inserts a new entity of type T into the database.

This method ensures the entity is not nil before attempting to create it in the database. It leverages GORM's Create method, which persists the entity's data into the corresponding table in the database. If the operation is successful, it returns nil, indicating no error occurred. If the operation fails, it returns an error, which could be due to constraints like unique violations, missing required fields, or database connectivity issues.

Usage: err := repo.Create(&entity)

if err != nil {
    // Handle error
}

Parameters:

  • entity: A pointer to an instance of type T that represents the entity to be created in the database. The entity should be a valid non-nil pointer to a struct that GORM can map to a database table.

Returns: - nil if the entity is successfully created in the database. - An error if the entity is nil or if GORM encounters any issues while creating the record.

func (*Repository[T]) Delete

func (r *Repository[T]) Delete(entity *T) error

Delete removes an entity from the database.

This method takes an entity as an argument, ensures it is not nil, and then uses GORM's Delete method to delete the corresponding record from the database. If the operation is successful, it returns nil. If the operation fails, an error is returned, which could be due to database connectivity issues or other constraints.

Usage: err := repo.Delete(&entity)

if err != nil {
    // Handle error
}

Parameters:

  • entity: A pointer to an instance of type T that represents the entity to be deleted from the database. It should not be nil.

Returns: - nil if the entity is successfully deleted from the database. - An error if the entity is nil or if GORM encounters any issues while deleting the record.

func (*Repository[T]) DeleteById

func (r *Repository[T]) DeleteById(id interface{}) error

DeleteById removes an entity from the database using its ID.

This method takes an ID as an argument, ensures it is not nil, and then uses GORM's Delete method to delete the corresponding record from the database. The repository's primary key name is used in the query condition. If the operation is successful, it returns nil. If the operation fails, an error is returned, which could be due to database connectivity issues or other constraints.

Usage: err := repo.DeleteById(id)

if err != nil {
    // Handle error
}

Parameters:

  • id: An interface{} representing the ID of the entity to be deleted from the database. It should not be nil.

Returns: - nil if the entity is successfully deleted from the database. - An error if the ID is nil or if GORM encounters any issues while deleting the record.

func (*Repository[T]) Get

func (r *Repository[T]) Get(entity T) (*T, error)

Get retrieves a single entity from the database based on the provided filter criteria. It takes a pointer to the repository, an entity object as a filter, and returns a pointer to the retrieved entity and an error, if any.

Example:

userRepo, err := NewUserRepository(db)
if err != nil {
	// Handle error
}

// Create a sample user entity for filtering
filterUser := User{ID: 1}

// Retrieve the user entity from the database based on the filter
retrievedUser, err := userRepo.Get(filterUser)
if err != nil {
	// Handle error
}

Parameters: - entity: An object of the entity type with the filter criteria.

Returns: - A pointer to the retrieved entity. - An error if the retrieval operation encounters any issues.

func (*Repository[T]) GetById

func (r *Repository[T]) GetById(id interface{}) (*T, error)

GetById retrieves a single entity from the database based on its unique identifier (id). It takes a pointer to the repository and the id of the entity, and returns a pointer to the retrieved entity and an error, if any.

Example:

userRepo, err := NewUserRepository(db)
if err != nil {
	// Handle error
}

// Provide the unique identifier for the user to be retrieved
userId := 1

// Retrieve the user entity from the database based on the unique identifier
retrievedUser, err := userRepo.GetById(userId)
if err != nil {
	// Handle error
}

Parameters: - id: The unique identifier of the entity.

Returns: - A pointer to the retrieved entity. - An error if the retrieval operation encounters any issues, including if the provided id is nil.

func (*Repository[T]) GetLatest

func (r *Repository[T]) GetLatest() (*T, error)

GetLatest retrieves the latest entity from the database without any filter criteria. It takes a pointer to the repository and returns a pointer to the retrieved entity and an error, if any.

Example:

userRepo, err := NewUserRepository(db)
if err != nil {
	// Handle error
}

// Retrieve the latest user entity from the database
latestUser, err := userRepo.GetLatest()
if err != nil {
	// Handle error
}

Returns: - A pointer to the retrieved entity. - An error if the retrieval operation encounters any issues.

func (*Repository[T]) Search

func (r *Repository[T]) Search(page uint, query interface{}, args ...interface{}) (Pagination[T], error)

Search performs a paginated search for entities in the database based on given criteria.

This method takes a GORM query condition, performs a paginated search using GORM's Find method, and returns the paginated results. The paginated results include the entities found and additional information such as total count and pagination details.

Usage: query := "your_column = ?" args := []interface{}{"your_value"} pagination, err := repo.Search(page, query, args...)

if err != nil {
    // Handle error
}

// Use pagination for further processing

Parameters: - page: The page number for pagination (starting from 1). - query: GORM query condition. - args: Arguments for the query condition.

Returns: - A structure containing the paginated search results, including entities, total count, and pagination details. - An error if the search operation encounters any issues.

func (*Repository[T]) SearchAll

func (r *Repository[T]) SearchAll(query interface{}, args ...interface{}) ([]T, error)

SearchAll performs a paginated search for all entities in the database based on given criteria.

This method takes a GORM query condition, performs a paginated search using GORM's Find method, and returns the paginated results. The paginated results include all entities found and additional information such as total count and pagination details.

Usage: query := "your_column = ?" args := []interface{}{"your_value"} pagination, err := repo.SearchAll(query, args...)

if err != nil {
    // Handle error
}

// Use pagination for further processing

Parameters: - query: GORM query condition. - args: Arguments for the query condition.

Returns: - A structure containing the paginated search results, including entities, total count, and pagination details. - An error if the search operation encounters any issues.

func (*Repository[T]) Update

func (r *Repository[T]) Update(entity *T) error

Update modifies an existing entity of type T in the database.

This method ensures the entity is not nil before attempting to update it in the database. It uses GORM's Save method, which updates the entity's data in the corresponding table in the database. If the operation is successful, it returns nil, indicating no error occurred. If the operation fails, it returns an error, which could be due to constraints like unique violations, missing required fields, or database connectivity issues.

Usage: err := repo.Update(&entity)

if err != nil {
    // Handle error
}

Parameters:

  • entity: A pointer to an instance of type T that represents the entity to be updated in the database. The entity should be a valid non-nil pointer to a struct that GORM can map to a database table.

Returns: - nil if the entity is successfully updated in the database. - An error if the entity is nil or if GORM encounters any issues while updating the record.

type Response

type Response[T any] struct {
	Entities    []T   `json:"entities"`
	TotalCount  int64 `json:"totalCount"`
	Page        uint  `json:"page"`
	PageSize    uint  `json:"pageSize"`
	TotalPages  int64 `json:"totalPages"`
	HasNextPage bool  `json:"hasNextPage"`
	HasPrevPage bool  `json:"hasPrevPage"`
}

Response represents the paginated search results including entities, total count, and pagination details.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL