github.com/dhax/go-base@v0.0.0-20231004214136-8be7e5c1972b/api/app/api.go (about)

     1  // Package app ties together application resources and handlers.
     2  package app
     3  
     4  import (
     5  	"net/http"
     6  
     7  	"github.com/go-chi/chi/v5"
     8  	"github.com/go-pg/pg"
     9  	"github.com/sirupsen/logrus"
    10  
    11  	"github.com/dhax/go-base/database"
    12  	"github.com/dhax/go-base/logging"
    13  )
    14  
    15  type ctxKey int
    16  
    17  const (
    18  	ctxAccount ctxKey = iota
    19  	ctxProfile
    20  )
    21  
    22  // API provides application resources and handlers.
    23  type API struct {
    24  	Account *AccountResource
    25  	Profile *ProfileResource
    26  }
    27  
    28  // NewAPI configures and returns application API.
    29  func NewAPI(db *pg.DB) (*API, error) {
    30  	accountStore := database.NewAccountStore(db)
    31  	account := NewAccountResource(accountStore)
    32  
    33  	profileStore := database.NewProfileStore(db)
    34  	profile := NewProfileResource(profileStore)
    35  
    36  	api := &API{
    37  		Account: account,
    38  		Profile: profile,
    39  	}
    40  	return api, nil
    41  }
    42  
    43  // Router provides application routes.
    44  func (a *API) Router() *chi.Mux {
    45  	r := chi.NewRouter()
    46  
    47  	r.Mount("/account", a.Account.router())
    48  	r.Mount("/profile", a.Profile.router())
    49  
    50  	return r
    51  }
    52  
    53  func log(r *http.Request) logrus.FieldLogger {
    54  	return logging.GetLogEntry(r)
    55  }