Erstes Commit

This commit is contained in:
2026-07-12 02:49:54 +02:00
commit 6dd456ca4a
15 changed files with 920 additions and 0 deletions

View File

@@ -0,0 +1,147 @@
package pocketbase
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
)
// Client handles interactions with the PocketBase API.
type Client struct {
baseURL string
user string
password string
category string
http *http.Client
}
// New creates a new PocketBase client.
func New(baseURL, user, password, category string) *Client {
// Normalise: ensure baseURL does not already end with /api.
baseURL = strings.TrimSuffix(baseURL, "/api")
baseURL = strings.TrimSuffix(baseURL, "/")
return &Client{
baseURL: baseURL,
user: user,
password: password,
category: category,
http: &http.Client{
Timeout: 30 * time.Second,
},
}
}
type authRequest struct {
Identity string `json:"identity"`
Password string `json:"password"`
}
type authResponse struct {
Token string `json:"token"`
}
type record struct {
URL string `json:"url"`
}
type recordsResponse struct {
Items []record `json:"items"`
}
// GetBookmarkURLs authenticates and retrieves URLs from the bookmarks collection.
func (c *Client) GetBookmarkURLs(ctx context.Context) ([]string, error) {
token, err := c.authenticate(ctx)
if err != nil {
return nil, fmt.Errorf("pocketbase auth: %w", err)
}
urls, err := c.fetchURLs(ctx, token)
if err != nil {
return nil, fmt.Errorf("pocketbase fetch URLs: %w", err)
}
return urls, nil
}
func (c *Client) authenticate(ctx context.Context) (string, error) {
reqBody, err := json.Marshal(authRequest{
Identity: c.user,
Password: c.password,
})
if err != nil {
return "", err
}
authURL := c.baseURL + "/api/collections/users/auth-with-password"
req, err := http.NewRequestWithContext(ctx, "POST", authURL, bytes.NewBuffer(reqBody))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.http.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("unexpected status: %d", resp.StatusCode)
}
var authResp authResponse
if err := json.NewDecoder(resp.Body).Decode(&authResp); err != nil {
return "", err
}
return authResp.Token, nil
}
func (c *Client) fetchURLs(ctx context.Context, token string) ([]string, error) {
// Filter: category=<value>, perPage=200, fields=url
filter := fmt.Sprintf(`category="%s"`, c.category)
u, err := url.Parse(c.baseURL + "/api/collections/bookmarks/records")
if err != nil {
return nil, fmt.Errorf("invalid base URL: %w", err)
}
q := u.Query()
q.Set("filter", filter)
q.Set("perPage", "200")
q.Set("fields", "url")
u.RawQuery = q.Encode()
req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
req.Header.Set("Authorization", token)
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)
}
var recs recordsResponse
if err := json.NewDecoder(resp.Body).Decode(&recs); err != nil {
return nil, err
}
var urls []string
for _, r := range recs.Items {
if r.URL != "" {
urls = append(urls, r.URL)
}
}
return urls, nil
}

View File

@@ -0,0 +1,65 @@
package pocketbase
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestGetBookmarkURLs_Success(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/collections/users/auth-with-password" {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(authResponse{Token: "test-token"})
return
}
if r.URL.Path == "/api/collections/bookmarks/records" {
if r.Header.Get("Authorization") != "test-token" {
t.Errorf("Expected Authorization header 'test-token', got '%s'", r.Header.Get("Authorization"))
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(recordsResponse{
Items: []record{
{URL: "https://royalroad.com/fiction/1"},
{URL: "https://royalroad.com/fiction/2"},
},
})
return
}
t.Errorf("Unexpected request to %s", r.URL.Path)
}))
defer server.Close()
client := New(server.URL, "user", "pass", "Geschichten")
urls, err := client.GetBookmarkURLs(context.Background())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(urls) != 2 {
t.Errorf("Expected 2 URLs, got %d", len(urls))
}
if urls[0] != "https://royalroad.com/fiction/1" {
t.Errorf("Unexpected first URL: %s", urls[0])
}
}
func TestGetBookmarkURLs_AuthFailure(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/collections/users/auth-with-password" {
w.WriteHeader(http.StatusUnauthorized)
return
}
t.Errorf("Unexpected request to %s", r.URL.Path)
}))
defer server.Close()
client := New(server.URL, "user", "pass", "Geschichten")
_, err := client.GetBookmarkURLs(context.Background())
if err == nil {
t.Error("Expected error on auth failure, got nil")
}
}