Skip to content

Repositories ​

A repository gives application services methods for reading and writing records. Keep database queries in the repository so the same service can run from a controller, command, job, or schedule.

Generate a Repository ​

Apply the photos migration before generating the repository. make:model reads the table from the default database connection.

bash
forj make:model photos --package photos --no-open

The command writes Photo and PhotoRepo to internal/photos/photo.go and registers the repository constructor in app/wire/inject_repositories_app.go. For relationships and regeneration behavior, see the make:model reference.

Add internal/photos/queries.go for the lookup your feature needs. WithContext carries the caller's cancellation and deadline into the database call.

go
package photos

import "context"

// ListNewest returns photos in reverse creation order.
func (r *PhotoRepo) ListNewest(ctx context.Context) ([]Photo, error) {
	db, err := r.WithContext(ctx).Builder()
	if err != nil {
		return nil, err
	}
	var photos []Photo
	if err := db.Order("created_at DESC").Find(&photos).Error; err != nil {
		return nil, err
	}
	return photos, nil
}

Run forj build to compile the query and refresh the App's Wire graph. Then test the query with two rows in a temporary database.

Test the Query ​

Add internal/photos/queries_test.go. Replace your/module in the imports with the module path from go.mod. The test uses a temporary SQLite file and creates its fixture table from Photo. Use Migrations to apply schema changes to the App database.

go
package photos

import (
	"context"
	"path/filepath"
	"testing"
	"time"

	"your/module/internal/database"
	"your/module/internal/inspects"
)

// TestListNewest verifies the query orders persisted photos newest first.
func TestListNewest(t *testing.T) {
	t.Setenv("DB_DEFAULT", "default")
	t.Setenv("DB_DRIVER", "sqlite")
	t.Setenv("DB_DATABASE", filepath.Join(t.TempDir(), "photos.db"))
	connections := database.NewConnections(inspects.NewManager())
	t.Cleanup(func() {
		if err := connections.Close(context.Background()); err != nil {
			t.Error(err)
		}
	})
	db, err := connections.Default()
	if err != nil {
		t.Fatal(err)
	}
	if err := db.AutoMigrate(&Photo{}); err != nil {
		t.Fatal(err)
	}

	ctx := t.Context()
	repo := NewPhotoRepo(connections).WithContext(ctx)
	for index, key := range []string{"older.jpg", "newer.jpg"} {
		photo := Photo{StorageKey: key, CreatedAt: time.Unix(int64(index), 0).UTC()}
		if err := repo.Create(&photo); err != nil {
			t.Fatal(err)
		}
	}
	got, err := repo.ListNewest(ctx)
	if err != nil {
		t.Fatal(err)
	}
	if len(got) != 2 || got[0].StorageKey != "newer.jpg" || got[1].StorageKey != "older.jpg" {
		t.Fatalf("photos = %+v, want newer.jpg then older.jpg", got)
	}
}

From the Project root, run the focused test. A pass means the repository read the two saved rows in the expected order.

bash
go test ./internal/photos -run '^TestListNewest$'

Run go test ./... to verify callers too. Use an integration test against MySQL or PostgreSQL when you depend on that database's SQL, locking, or transaction behavior.

Repository Shape ​

When a repository needs custom construction, take the App's generated database connections as a constructor dependency.

go
package users

type Repository struct {
	db *gorm.DB
}

func NewRepository(conns *database.Connections) (*Repository, error) {
	db, err := conns.Default()
	if err != nil {
		return nil, err
	}
	return &Repository{db: db}, nil
}

Use the database accessors generated for your App. Keep backend connection selection outside business logic.

Register repository constructors through app/wire/inject_repositories_app.go. Additional apps use the owning app's app/<name>/wire/inject_repositories_app.go.

Responsibilities ​

Repositories should own:

  • query construction
  • persistence-specific models
  • transaction participation
  • mapping between database rows and application types
  • database error interpretation

Repositories should not own HTTP behavior, CLI output, queue dispatch policy, event fan-out policy, or scheduler behavior.

Service Boundary ​

When a service needs this query, add *PhotoRepo to the service's constructor. Wire can supply it because make:model registered the constructor in the App's repository set. Keep the service inputs independent of database records unless a record is intentionally your application type.

Named Connections ​

Use a named connection when the feature uses a separate database, such as one for analytics. Select the generated accessor in the repository's constructor.

Next Steps ​