josie / simplegit

package web

import (
	"errors"
	"net/http"

	"git.josie-c.com/josie/simplegit/internal/db"
)

// profileData is the model for a user's profile page: their repos plus the
// viewer's identity, so the owner sees account actions.
type profileData struct {
	Username string
	Profile  string
	IsSelf   bool
	Repos    []repoItem
}

func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) {
	name := r.PathValue("user")
	profileUser, err := db.GetUserByName(s.database, name)
	if errors.Is(err, db.ErrNotFound) {
		http.NotFound(w, r)
		return
	}
	if err != nil {
		s.internalError(w, r, err)
		return
	}

	viewer := currentUser(r)
	data := profileData{Profile: profileUser.Username}
	var viewerID int64
	if viewer != nil {
		data.Username = viewer.Username
		viewerID = viewer.ID
		data.IsSelf = viewer.ID == profileUser.ID
	}

	repos, err := db.ListRepos(s.database, viewerID)
	if err != nil {
		s.internalError(w, r, err)
		return
	}
	data.Repos = repoItems(repos, name)
	s.render(w, "profile.html", http.StatusOK, data)
}