aboutsummaryrefslogtreecommitdiff
path: root/backend/general/records.go
blob: d623862a2df8d423f02c373b540d919caf33942e (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
package general

import (
	"encoding/json"
	"fmt"
	"io"
	"log/slog"
	"net/http"
)

type RawRecord struct {
	URI   string          `json:"uri"`
	Value json.RawMessage `json:"value"`
}

func FetchRawRecordCollection(logger *slog.Logger, did, collection, baseURL string) ([]RawRecord, error) {
	url := fmt.Sprintf("%s/xrpc/com.atproto.repo.listRecords?repo=%s&collection=%s", baseURL, did, collection)

	logger.Debug("fetching raw record collection", "did", did, "endpoint", baseURL, "collection", collection)

	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		body, _ := io.ReadAll(resp.Body)
		return nil, fmt.Errorf("server returned %d: %s", resp.StatusCode, string(body))
	}

	var result struct {
		Records []RawRecord `json:"records"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return nil, err
	}

	return result.Records, nil
}

func FetchRawRecordByURI(logger *slog.Logger, uri, baseURL string) (*RawRecord, error) {
	repo, collection, rkey, err := ParseURI(uri)
	if err != nil {
		return nil, err
	}

	url := fmt.Sprintf("%s/xrpc/com.atproto.repo.getRecord?repo=%s&collection=%s&rkey=%s",
		baseURL, repo, collection, rkey)

	logger.Debug("fetching raw record by URI", "uri", uri, "endpoint", baseURL)

	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		body, _ := io.ReadAll(resp.Body)
		return nil, fmt.Errorf("endpoint returned %d: %s", resp.StatusCode, string(body))
	}

	var result RawRecord
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return nil, err
	}

	return &result, nil
}