add API boilerplate + /accounts/{accountID} and /accounts/@me endpoints
This commit is contained in:
parent
0fa769a248
commit
dfc116d828
7 changed files with 335 additions and 0 deletions
48
web/api/accounts/get_account.go
Normal file
48
web/api/accounts/get_account.go
Normal file
|
@ -0,0 +1,48 @@
|
|||
package accounts
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.sleepycat.moe/sam/mercury/internal/database/sql"
|
||||
"git.sleepycat.moe/sam/mercury/web/api"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/oklog/ulid/v2"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func (app *App) GetID(w http.ResponseWriter, r *http.Request) (any, error) {
|
||||
ctx := r.Context()
|
||||
|
||||
accountID, err := ulid.Parse(chi.URLParam(r, "accountID"))
|
||||
if err != nil {
|
||||
return nil, api.Error{Code: api.ErrAccountNotFound}
|
||||
}
|
||||
|
||||
acct, err := app.Account().ByID(ctx, accountID)
|
||||
if err != nil {
|
||||
if err == sql.ErrNotFound {
|
||||
return nil, api.Error{Code: api.ErrAccountNotFound}
|
||||
}
|
||||
|
||||
log.Err(err).Str("id", accountID.String()).Msg("fetching user from database")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
token, ok := app.TokenFromContext(ctx)
|
||||
if ok && token.UserID == acct.ID {
|
||||
return api.DBAccountToSelfAccount(acct), nil
|
||||
}
|
||||
return api.DBAccountToAccount(acct), nil
|
||||
}
|
||||
|
||||
func (app *App) GetMe(w http.ResponseWriter, r *http.Request) (api.SelfAccount, error) {
|
||||
ctx := r.Context()
|
||||
token, _ := app.TokenFromContext(ctx) // Token will always be available
|
||||
|
||||
acct, err := app.Account().ByID(ctx, token.UserID)
|
||||
if err != nil {
|
||||
log.Err(err).Str("id", token.UserID.String()).Msg("fetching user from database")
|
||||
return api.SelfAccount{}, err
|
||||
}
|
||||
return api.DBAccountToSelfAccount(acct), nil
|
||||
}
|
13
web/api/accounts/module.go
Normal file
13
web/api/accounts/module.go
Normal file
|
@ -0,0 +1,13 @@
|
|||
package accounts
|
||||
|
||||
import "git.sleepycat.moe/sam/mercury/web/app"
|
||||
|
||||
type App struct {
|
||||
*app.App
|
||||
}
|
||||
|
||||
func New(app *app.App) *App {
|
||||
return &App{
|
||||
App: app,
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue