commit 66567411879cb5e5bc98180fc1249843bba6267e
parent 0bb2f404289bd4f1768b378011e5882eefdf16cb
Author: MTRNord <mtrnord1@gmail.com>
Date: Sun, 18 Feb 2018 20:54:45 +0100
Implement "POST /papers" Endpoint and fix the content of that Endpoint in the Definitions file
Diffstat:
2 files changed, 77 insertions(+), 7 deletions(-)
diff --git a/api/openapi.yaml b/api/openapi.yaml
@@ -54,7 +54,8 @@ paths:
content:
application/json:
schema:
- type: object
+ type: array
+ items:
properties:
name:
type: string
diff --git a/api/webserver.go b/api/webserver.go
@@ -9,6 +9,7 @@ import (
"github.com/dgraph-io/badger"
"github.com/gorilla/mux"
"github.com/pkg/errors"
+ "github.com/satori/go.uuid"
"net/http"
"os"
"path/filepath"
@@ -49,15 +50,83 @@ type Author struct {
}
func Papers(w http.ResponseWriter, r *http.Request) {
- papers, err := getPapers()
+ switch r.Method {
+ case "GET":
+ papers, err := getPapers()
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("API-VERSION", "0.0.0")
+ w.WriteHeader(http.StatusOK)
+ w.Write(papers)
+ case "POST":
+ decoder := json.NewDecoder(r.Body)
+ var t []Paper
+ err := decoder.Decode(&t)
+ if err != nil {
+ panic(err)
+ }
+ defer r.Body.Close()
+
+ papers, err := addPapers(t)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("API-VERSION", "0.0.0")
+ w.WriteHeader(http.StatusOK)
+ w.Write(papers)
+ }
+}
+
+func addPapers(data []Paper) ([]byte, error) {
+ papersDB, openErr := db.OpenDB()
+ if openErr != nil {
+ return nil, openErr
+ }
+
+ var papers []Paper
+
+ for _, p := range data {
+ puuid := uuid.NewV4()
+ newUUID := puuid.String()
+ newName := p.Name
+ newDesc := p.Description
+ newAuthor := p.Author.UUID
+
+ DBErr := papersDB.Update(func(txn *badger.Txn) error {
+ nameErr := txn.Set([]byte(fmt.Sprintf("papers|paper|%s|name", newUUID)), []byte(newName))
+ if nameErr != nil {
+ return nameErr
+ }
+
+ descErr := txn.Set([]byte(fmt.Sprintf("papers|paper|%s|description", newUUID)), []byte(newDesc))
+ if descErr != nil {
+ return descErr
+ }
+
+ return txn.Set([]byte(fmt.Sprintf("papers|paper|%s|author", newUUID)), []byte(newAuthor))
+ })
+ if DBErr != nil {
+ return nil, DBErr
+ }
+
+ paper := Paper{}
+ paper.UUID = newUUID
+ paper.Name = newName
+
+ papers = append(papers, paper)
+ }
+
+ papersArray, err := json.Marshal(papers)
if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
+ return nil, err
}
- w.Header().Set("Content-Type", "application/json")
- w.Header().Set("API-VERSION", "0.0.0")
- w.WriteHeader(http.StatusOK)
- w.Write(papers)
+ return papersArray, nil
}
func getPapers() ([]byte, error) {