Skip to content

Commit

Permalink
added universal request handler for simple functions
Browse files Browse the repository at this point in the history
  • Loading branch information
dvovk committed Mar 18, 2024
1 parent a5e2e33 commit 2127dd8
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
28 changes: 28 additions & 0 deletions api/api_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,33 @@ func (h *APIHandler) findNodeClient(w http.ResponseWriter, r *http.Request) (eri
return nil, fmt.Errorf("unknown sessionId: %s", sessionId)
}

func (h *APIHandler) UniversalRequest(w http.ResponseWriter, r *http.Request) {
apiStr := chi.URLParam(r, "*")

client, err := h.findNodeClient(w, r)

if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

response, err := client.GetResponse(r.Context(), apiStr)

if err != nil {
http.Error(w, fmt.Sprintf("Unable to fetch snapshot files list: %v", err), http.StatusInternalServerError)
return
}

jsonData, err := json.Marshal(response)

if err != nil {
api_internal.EncodeError(w, r, err)
}

w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}

func NewAPIHandler(
sessions sessions.CacheService,
erigonNode erigon_node.Client,
Expand Down Expand Up @@ -498,6 +525,7 @@ func NewAPIHandler(
r.Get("/sessions/{sessionId}/nodes/{nodeId}/bootnodes", r.Bootnodes)
r.Get("/sessions/{sessionId}/nodes/{nodeId}/snapshot-sync", r.ShanphotSync)
r.Get("/sessions/{sessionId}/nodes/{nodeId}/snapshot-files-list", r.ShanphotFilesList)
r.Get("/v2/sessions/{sessionId}/nodes/{nodeId}/*", r.UniversalRequest)

return r
}
Expand Down
24 changes: 24 additions & 0 deletions internal/erigon_node/erigon_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,28 @@ func (c *NodeClient) fetch(ctx context.Context, method string, params url.Values
return nodeRequest, nil
}

func (c *NodeClient) GetResponse(ctx context.Context, api string) (interface{}, error) {
var response interface{}

request, err := c.fetch(ctx, api, nil)

if err != nil {
return response, err
}

_, result, err := request.nextResult(ctx)

if err != nil {
return response, err
}

if err := json.Unmarshal(result, &response); err != nil {
return response, err
}

return response, nil
}

func NewErigonNodeClient() Client {
return &NodeClient{}
}
Expand Down Expand Up @@ -226,6 +248,8 @@ type Client interface {
ShanphotSync(ctx context.Context) (DownloadStatistics, error)
ShanphotFiles(ctx context.Context) (ShanshotFilesList, error)

GetResponse(ctx context.Context, api string) (interface{}, error)

// TODO: refactor the following methods to follow above pattern where appropriate
BodiesDownload(ctx context.Context, w http.ResponseWriter)
HeadersDownload(ctx context.Context, w http.ResponseWriter)
Expand Down

0 comments on commit 2127dd8

Please sign in to comment.