Skip to content

Commit

Permalink
feat(api): Unpack endpoint gets a zip and sends back its contents
Browse files Browse the repository at this point in the history
  • Loading branch information
dustmop committed Oct 9, 2018
1 parent 00199a9 commit 185c01a
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ func NewServerRoutes(s *Server) *http.ServeMux {
m.Handle("/export/", s.middleware(dsh.ZipDatasetHandler))
m.Handle("/diff", s.middleware(dsh.DiffHandler))
m.Handle("/body/", s.middleware(dsh.BodyHandler))
m.Handle("/unpack/", s.middleware(dsh.UnpackHandler))

renderh := NewRenderHandlers(s.qriNode.Repo)
m.Handle("/render/", s.middleware(renderh.RenderHandler))
Expand Down
50 changes: 50 additions & 0 deletions api/datasets.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package api

import (
"archive/zip"
"bytes"
"encoding/json"
"errors"
Expand Down Expand Up @@ -176,6 +177,23 @@ func (h *DatasetHandlers) BodyHandler(w http.ResponseWriter, r *http.Request) {
}
}

// UnpackHandler unpacks a zip file and sends it back as json
func (h *DatasetHandlers) UnpackHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "OPTIONS":
util.EmptyOkHandler(w, r)
case "POST":
postData, err := ioutil.ReadAll(r.Body)
if err != nil {
util.WriteErrResponse(w, http.StatusBadRequest, err)
return
}
h.unpackHandler(w, r, postData)
default:
util.NotFoundHandler(w, r)
}
}

// ZipDatasetHandler is the endpoint for getting a zip archive of a dataset
func (h *DatasetHandlers) ZipDatasetHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
Expand Down Expand Up @@ -765,3 +783,35 @@ func (h DatasetHandlers) bodyHandler(w http.ResponseWriter, r *http.Request) {
log.Infof("error writing response: %s", err.Error())
}
}

func (h DatasetHandlers) unpackHandler(w http.ResponseWriter, r *http.Request, postData []byte) {
zr, err := zip.NewReader(bytes.NewReader(postData), int64(len(postData)))
if err != nil {
util.WriteErrResponse(w, http.StatusInternalServerError, err)
return
}
// Create a map from filenames in the zip to their json encoded contents.
contents := make(map[string]string)
for _, f := range zr.File {
rc, err := f.Open()
if err != nil {
util.WriteErrResponse(w, http.StatusInternalServerError, err)
return
}
data, err := ioutil.ReadAll(rc)
if err != nil {
util.WriteErrResponse(w, http.StatusInternalServerError, err)
return
}
contents[f.Name] = string(data)
}
data, err := json.Marshal(contents)
if err != nil {
util.WriteErrResponse(w, http.StatusInternalServerError, err)
return
}
// Send response.
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(data)
}

0 comments on commit 185c01a

Please sign in to comment.