Skip to content

Commit

Permalink
add get by id to endpoint (#2107)
Browse files Browse the repository at this point in the history
  • Loading branch information
srliao authored Mar 21, 2024
1 parent 47f0c1d commit 119a0ed
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
36 changes: 36 additions & 0 deletions backend/pkg/api/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"

"github.com/genshinsim/gcsim/backend/pkg/services/db"
"github.com/go-chi/chi"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
Expand Down Expand Up @@ -107,3 +108,38 @@ func (s *Server) getDB() http.HandlerFunc {
// w.Write(data)
}
}

func (s *Server) getByID() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
key := chi.URLParam(r, "id")

resp, err := s.dbClient.GetOne(r.Context(), &db.GetOneRequest{Id: key})
if err != nil {
if st, ok := status.FromError(err); st.Code() == codes.NotFound && ok {
http.Error(w, "not found", http.StatusNotFound)
return
}
http.Error(w, "internal server error", http.StatusInternalServerError)
s.Log.Errorw("unexpected error getting share", "err", err)
return
}
data, err := marshalOptions().Marshal(resp.GetData())
if err != nil {
s.Log.Warnw("error query db - cannot marshal result", "err", err)
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
writer, err := gzip.NewWriterLevel(w, gzip.BestCompression)
if err != nil {
s.Log.Warnw("error query db - cannot write gzip result", "err", err)
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
defer writer.Close()

w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Encoding", "gzip")
w.WriteHeader(http.StatusOK)
writer.Write(data)
}
}
1 change: 1 addition & 0 deletions backend/pkg/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ func (s *Server) routes() {

r.Route("/db", func(r chi.Router) {
r.Get("/", s.getDB())
r.Get("/id/{id}", s.getByID())
})
})
}

0 comments on commit 119a0ed

Please sign in to comment.