databag/net/server/internal/api_getChannelTopicSubjectField.go

57 lines
1.3 KiB
Go
Raw Normal View History

2022-03-02 21:19:16 +00:00
package databag
import (
2022-07-22 19:28:14 +00:00
"bytes"
"databag/internal/store"
"encoding/base64"
"errors"
"github.com/gorilla/mux"
"github.com/valyala/fastjson"
"gorm.io/gorm"
"net/http"
"strings"
"time"
2022-03-02 21:19:16 +00:00
)
func GetChannelTopicSubjectField(w http.ResponseWriter, r *http.Request) {
2022-07-22 19:28:14 +00:00
// scan parameters
params := mux.Vars(r)
topicID := params["topicID"]
field := params["field"]
elements := strings.Split(field, ".")
2022-03-02 21:19:16 +00:00
2022-07-27 05:43:39 +00:00
channelSlot, _, code, err := getChannelSlot(r, false)
2022-07-22 19:28:14 +00:00
if err != nil {
ErrResponse(w, code, err)
return
}
2022-03-02 21:19:16 +00:00
2022-07-22 19:28:14 +00:00
// load topic
var topicSlot store.TopicSlot
if err = store.DB.Where("channel_id = ? AND topic_slot_id = ?", channelSlot.Channel.ID, topicID).First(&topicSlot).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
code = http.StatusNotFound
} else {
code = http.StatusInternalServerError
}
2022-07-22 20:23:17 +00:00
ErrResponse(w, code, err)
2022-07-22 19:28:14 +00:00
return
}
if topicSlot.Topic == nil {
ErrResponse(w, http.StatusNotFound, errors.New("referenced missing topic"))
return
}
2022-03-02 21:19:16 +00:00
2022-07-22 19:28:14 +00:00
// decode data
strData := fastjson.GetString([]byte(topicSlot.Topic.Data), elements...)
binData, err := base64.StdEncoding.DecodeString(strData)
if err != nil {
ErrResponse(w, http.StatusNotFound, err)
return
}
2022-03-02 21:19:16 +00:00
2022-07-22 19:28:14 +00:00
// response with content
http.ServeContent(w, r, field, time.Unix(topicSlot.Topic.Updated, 0), bytes.NewReader(binData))
2022-03-02 21:19:16 +00:00
}