summaryrefslogtreecommitdiff
path: root/srv/api/chat.go
blob: 84fffdea0a550baf608882836adc6997dfaf2f84 (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
package api

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/mediocregopher/blog.mediocregopher.com/srv/chat"
)

func (a *api) chatHistoryHandler() http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		limit, err := strToInt(r.FormValue("limit"), 0)
		if err != nil {
			badRequest(rw, r, fmt.Errorf("invalid limit parameter: %w", err))
			return
		}

		cursor := r.FormValue("cursor")

		cursor, msgs, err := a.params.GlobalRoom.History(r.Context(), chat.HistoryOpts{
			Limit:  limit,
			Cursor: cursor,
		})

		if argErr := (chat.ErrInvalidArg{}); errors.As(err, &argErr) {
			badRequest(rw, r, argErr.Err)
			return
		} else if err != nil {
			internalServerError(rw, r, err)
		}

		jsonResult(rw, r, struct {
			Cursor   string         `json:"cursor"`
			Messages []chat.Message `json:"messages"`
		}{
			Cursor:   cursor,
			Messages: msgs,
		})
	})
}