summaryrefslogtreecommitdiff
path: root/system/api/handlers.go
blob: 0c9139fbb9afb4bb701b6f8d4071e6f52910f68a (plain)
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package api

import (
	"bytes"
	"encoding/json"
	"log"
	"net/http"

	"github.com/bosssauce/ponzu/content"
	"github.com/bosssauce/ponzu/system/db"
)

func typesHandler(res http.ResponseWriter, req *http.Request) {
	var types = []string{}
	for t := range content.Types {
		types = append(types, string(t))
	}

	j, err := toJSON(types)
	if err != nil {
		res.WriteHeader(http.StatusInternalServerError)
		return
	}

	sendData(res, j, http.StatusOK)
}

func postsHandler(res http.ResponseWriter, req *http.Request) {
	q := req.URL.Query()
	t := q.Get("type")
	// TODO: implement pagination
	// num := q.Get("num")
	// page := q.Get("page")

	// TODO: inplement time-based ?after=time.Time, ?before=time.Time between=time.Time|time.Time

	if t == "" {
		res.WriteHeader(http.StatusBadRequest)
		return
	}

	posts := db.ContentAll(t)
	var all = []json.RawMessage{}
	for _, post := range posts {
		all = append(all, post)
	}

	j, err := fmtJSON(all...)
	if err != nil {
		res.WriteHeader(http.StatusInternalServerError)
		return
	}

	sendData(res, j, http.StatusOK)
}

func postHandler(res http.ResponseWriter, req *http.Request) {
	q := req.URL.Query()
	id := q.Get("id")
	t := q.Get("type")

	if t == "" || id == "" {
		res.WriteHeader(http.StatusBadRequest)
		return
	}

	post, err := db.Content(t + ":" + id)
	if err != nil {
		res.WriteHeader(http.StatusInternalServerError)
		return
	}

	j, err := fmtJSON(json.RawMessage(post))
	if err != nil {
		res.WriteHeader(http.StatusInternalServerError)
		return
	}

	sendData(res, j, http.StatusOK)
}

func fmtJSON(data ...json.RawMessage) ([]byte, error) {
	var msg = []json.RawMessage{}
	for _, d := range data {
		msg = append(msg, d)
	}

	resp := map[string][]json.RawMessage{
		"data": msg,
	}

	var buf = &bytes.Buffer{}
	enc := json.NewEncoder(buf)
	err := enc.Encode(resp)
	if err != nil {
		log.Println("Failed to encode data to JSON:", err)
		return nil, err
	}

	return buf.Bytes(), nil
}

func toJSON(data []string) ([]byte, error) {
	var buf = &bytes.Buffer{}
	enc := json.NewEncoder(buf)
	resp := map[string][]string{
		"data": data,
	}

	err := enc.Encode(resp)
	if err != nil {
		log.Println("Failed to encode data to JSON:", err)
		return nil, err
	}

	return buf.Bytes(), nil
}

func wrapJSON(json []byte) []byte {
	var buf = &bytes.Buffer{}
	buf.Write([]byte(`{"data":`))
	buf.Write(json)
	buf.Write([]byte(`}`))

	return buf.Bytes()
}

// sendData() should be used any time you want to communicate
// data back to a foreign client
func sendData(res http.ResponseWriter, data []byte, code int) {
	res.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type")
	res.Header().Set("Access-Control-Allow-Origin", "*")
	res.Header().Set("Content-Type", "application/json")
	res.WriteHeader(code)
	res.Write(data)
}

// SendPreflight is used to respond to a cross-origin "OPTIONS" request
func SendPreflight(res http.ResponseWriter) {
	res.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type")
	res.Header().Set("Access-Control-Allow-Origin", "*")
	res.WriteHeader(200)
	return
}

// SendJSON returns a Response to a client as JSON
func SendJSON(res http.ResponseWriter, j map[string]interface{}) {
	var data []byte
	var err error

	data, err = json.Marshal(j)
	if err != nil {
		data, _ = json.Marshal(map[string]interface{}{
			"status":  "fail",
			"message": err.Error(),
		})
	}

	sendData(res, data, 200)
}

// ResponseFunc ...
type ResponseFunc func(http.ResponseWriter, *http.Request)

// CORS wraps a HandleFunc to response to OPTIONS requests properly
func CORS(next http.HandlerFunc) http.HandlerFunc {
	return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		if req.Method == http.MethodOptions {
			SendPreflight(res)
			return
		}

		next.ServeHTTP(res, req)
	})
}