This repository has been archived by the owner on Feb 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
read.go
100 lines (89 loc) · 2.33 KB
/
read.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package handler
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/davecgh/go-spew/spew"
"github.com/exlibris-fed/exlibris/dto"
"github.com/exlibris-fed/exlibris/model"
"github.com/exlibris-fed/openlibrary-go"
"github.com/gorilla/mux"
)
// GetReads returns a list of books a user has read
func (h *Handler) GetReads(w http.ResponseWriter, r *http.Request) {
c := h.contextFromRequest(r)
userctx := c.Value(model.ContextKeyAuthenticatedUser)
if userctx == nil {
log.Println("User is nil")
w.WriteHeader(http.StatusUnauthorized)
return
}
user := userctx.(model.User)
reads := []model.Read{}
response := []dto.Book{}
h.db.Where("fk_user = ?", user.ID).Find(&reads)
for _, read := range reads {
log.Println(read.BookID)
book := model.Book{}
h.db.Where("key = ?", fmt.Sprintf("/works/%s", read.BookID)).First(&book)
spew.Dump(book)
response = append(response, dto.Book{ID: book.ID, Title: book.Title})
}
b, err := json.Marshal(response)
if err != nil {
log.Println("error marshalling json: " + err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(b)
}
func (h *Handler) Read(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(http.StatusOK)
return
}
vars := mux.Vars(r)
id := vars["book"]
c := h.contextFromRequest(r)
userctx := c.Value(model.ContextKeyAuthenticatedUser)
if userctx == nil {
log.Println("User is nil")
w.WriteHeader(http.StatusUnauthorized)
return
}
user := userctx.(model.User)
book := model.Book{}
h.db.Where("id = ?", fmt.Sprintf("/works/%s", id)).First(&book)
if book.ID == "" {
// fetch book from API
work, err := openlibrary.GetWorkByID(id)
if err != nil {
log.Println("Could not fetch work", id, "got error", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
log.Printf("%+v\n", work)
return
/*
book := model.NewBook(work.Key, work.Title, 0, "")
result := h.db.Create(book)
if result.Error != nil {
log.Println("Could not insert book into DB")
w.WriteHeader(http.StatusConflict)
return
}
*/
}
read := model.Read{
UserID: user.ID,
User: &user,
BookID: id,
Book: &book,
}
h.db.Create(&read)
log.Printf("%+v", read)
//go h.ap.Federate(c, user, read)
w.WriteHeader(http.StatusCreated)
}