diff --git a/main.go b/main.go index da558a8..0c43b50 100644 --- a/main.go +++ b/main.go @@ -67,6 +67,7 @@ func registerMuxHandlers(app *core.App) http.Handler { app.Router.HandleFunc("/my/characters", characters.GetMyCharacters(app)).Methods("GET") // Accounts + app.Router.HandleFunc("/accounts", accounts.GetAccounts(app)).Methods("GET") app.Router.HandleFunc("/accounts", accounts.CreateAccount(app)).Methods("POST") app.Router.HandleFunc("/accounts/{id}", accounts.GetAccountById(app)).Methods("GET") app.Router.HandleFunc("/accounts/{id}", accounts.UpdateAccount(app)).Methods("PATCH") diff --git a/pkg/accounts/handlers/GetAccounts.go b/pkg/accounts/handlers/GetAccounts.go new file mode 100644 index 0000000..1a136b4 --- /dev/null +++ b/pkg/accounts/handlers/GetAccounts.go @@ -0,0 +1,51 @@ +package handlers + +import ( + "encoding/json" + "net/http" + "strings" + + models "github.com/maxfelker/terra-major-api/pkg/accounts/models" + "github.com/maxfelker/terra-major-api/pkg/core" + "github.com/maxfelker/terra-major-api/pkg/utils" +) + +func GetAccounts(app *core.App) http.HandlerFunc { + return func(writer http.ResponseWriter, request *http.Request) { + email := request.URL.Query().Get("email") + + var accounts []models.Account + query := app.DB + + if email != "" { + query = query.Where("email LIKE ?", "%"+strings.TrimSpace(email)+"%") + } + + result := query.Find(&accounts) + if result.Error != nil { + utils.ReturnError(writer, result.Error.Error(), http.StatusInternalServerError) + return + } + + var baseAccounts []models.BaseAccount + for _, account := range accounts { + baseAccounts = append(baseAccounts, models.BaseAccount{ + ID: account.ID, + Email: account.Email, + Created: account.Created, + Updated: account.Updated, + }) + } + + response, err := json.Marshal(baseAccounts) + + if err != nil { + utils.ReturnError(writer, err.Error(), http.StatusInternalServerError) + return + } + + writer.Header().Set("Content-Type", "application/json") + writer.WriteHeader(http.StatusOK) + writer.Write(response) + } +}