Cookies management by TermsFeed Cookie Consent

Repository methods

Please consider supporting us by disabling your ad blocker

8/21

Our repository functions perform migration and basic CRUD operations:

  • Migrate(ctx context.Context) error - The method responsible for migrating the repository, i.e., adjusting the PostgreSQL table to the domain object and importing the initial data. In our case, this function will be responsible for creating a new websites table. So there is no need to log into the GUI database client and manually create the table. However, it is important to remember that this function should be executed first, before reading or writing to the database.
  • Create(ctx context.Context, website Website) (*Website, error) - Method that creates a new website record in the repository. It returns the website saved to the database with the generated ID or an error in case of problems.
  • All(ctx context.Context) ([]Website, error) - It extracts all records from the repository and returns as a slice or returns an error if there are problems.
  • GetByName(ctx context.Context, name string) (*Website, error) - Gets a single Website record with the specified name or returns an error if there are problems. The name of each Website must be unique, so there is no risk of having two records with the same name.
  • Update(ctx context.Context, id int64, updated Website) (*Website, error) - Updates the Website record with the id identifier with the values found in the updated struct. It returns the updated record or an error in case of problems.
  • Delete(ctx context.Context, id int64) error - Deletes a record with the id identifier and returns an error if there are problems.

As you can see, all of these methods return errors. Some of them may be due to the action of the user, for example, when someone tries to add a Website that already exists (with the same name). It is a good practice to define such errors and return them from the functions so that the application can handle them and respond with an appropriate error message to the user. We will do this on the next page.

website/repository.go

package website

import "context"

type Repository interface {
    Migrate(ctx context.Context) error
    Create(ctx context.Context, website Website) (*Website, error)
    All(ctx context.Context) ([]Website, error)
    GetByName(ctx context.Context, name string) (*Website, error)
    Update(ctx context.Context, id int64, updated Website) (*Website, error)
    Delete(ctx context.Context, id int64) error
}
8/21