Skip to content

Commit

Permalink
Merge pull request #16 from maxfelker/TM-168-accounts-list
Browse files Browse the repository at this point in the history
Added /accounts GET endpoint
  • Loading branch information
maxfelker authored Aug 4, 2024
2 parents e9ecf17 + d808e3b commit c905095
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
51 changes: 51 additions & 0 deletions pkg/accounts/handlers/GetAccounts.go
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit c905095

Please sign in to comment.