Spaces and pages: - Spaces inside workspaces, open or private, with admin/editor/commenter/viewer roles that cascade from the workspace role (rules in internal/access) - Page tree per space with fractional position keys, move with cycle checks, trash that hides whole subtrees, restore and permanent delete - OpenAPI, TypeScript client, and web app sidebar tree with drag-and-drop, page, space, trash and space settings views (EN + PL) Design system: - Tokens, type scale, radii and shadows from the design kit in @docwell/ui/theme.css; Inter, Source Serif 4 and JetBrains Mono bundled - Vue ports of Button, TextField, Badge, Callout, Icon, Breadcrumbs, SlashMenu and PageTreeItem, plus Logo; favicons and web manifest - Web app and admin panel restyled on the new tokens, in light and dark Also: fix the Vite dev server crashing on /config.json, and stop tracking the local Design/ and docs/ folders. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
248 lines
6.4 KiB
Go
248 lines
6.4 KiB
Go
// Package pocketbase is a minimal typed client for the PocketBase REST API,
|
|
// authenticated as a superuser. It is the only way docwell-server reaches the
|
|
// database service.
|
|
package pocketbase
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type Client struct {
|
|
baseURL string
|
|
email string
|
|
password string
|
|
http *http.Client
|
|
|
|
mu sync.Mutex
|
|
token string
|
|
}
|
|
|
|
func New(baseURL, email, password string) *Client {
|
|
return &Client{
|
|
baseURL: baseURL,
|
|
email: email,
|
|
password: password,
|
|
http: &http.Client{Timeout: 30 * time.Second},
|
|
}
|
|
}
|
|
|
|
// Error is a non-2xx response from PocketBase.
|
|
type Error struct {
|
|
Status int `json:"status"`
|
|
Message string `json:"message"`
|
|
Data map[string]FieldError `json:"data"`
|
|
// MFAID is set on a 401 when the first auth factor passed and MFA is required.
|
|
MFAID string `json:"mfaId"`
|
|
}
|
|
|
|
// FieldError is a per-field validation error in Error.Data.
|
|
type FieldError struct {
|
|
Code string `json:"code"`
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
func (e *Error) Error() string {
|
|
return fmt.Sprintf("pocketbase: %d %s", e.Status, e.Message)
|
|
}
|
|
|
|
// IsNotFound reports whether err is a PocketBase 404.
|
|
func IsNotFound(err error) bool {
|
|
var pbErr *Error
|
|
return errors.As(err, &pbErr) && pbErr.Status == http.StatusNotFound
|
|
}
|
|
|
|
// Health checks that PocketBase is up. It does not require authentication.
|
|
func (c *Client) Health(ctx context.Context) error {
|
|
return c.send(ctx, http.MethodGet, "/api/health", "", nil, nil)
|
|
}
|
|
|
|
// ListResult is one page of records.
|
|
type ListResult[T any] struct {
|
|
Page int `json:"page"`
|
|
PerPage int `json:"perPage"`
|
|
TotalItems int `json:"totalItems"`
|
|
TotalPages int `json:"totalPages"`
|
|
Items []T `json:"items"`
|
|
}
|
|
|
|
// ListOptions maps to PocketBase list query parameters.
|
|
type ListOptions struct {
|
|
Page int
|
|
PerPage int
|
|
Filter string
|
|
Sort string
|
|
// Expand lists relations to inline, e.g. "organization" or "user,workspace".
|
|
Expand string
|
|
// Fields limits the returned fields, e.g. "id,title" (skips large columns).
|
|
Fields string
|
|
}
|
|
|
|
func (o ListOptions) values() url.Values {
|
|
v := url.Values{}
|
|
if o.Page > 0 {
|
|
v.Set("page", fmt.Sprint(o.Page))
|
|
}
|
|
if o.PerPage > 0 {
|
|
v.Set("perPage", fmt.Sprint(o.PerPage))
|
|
}
|
|
if o.Filter != "" {
|
|
v.Set("filter", o.Filter)
|
|
}
|
|
if o.Sort != "" {
|
|
v.Set("sort", o.Sort)
|
|
}
|
|
if o.Expand != "" {
|
|
v.Set("expand", o.Expand)
|
|
}
|
|
if o.Fields != "" {
|
|
v.Set("fields", o.Fields)
|
|
}
|
|
return v
|
|
}
|
|
|
|
// List fetches a page of records from a collection.
|
|
func List[T any](ctx context.Context, c *Client, collection string, opts ListOptions) (ListResult[T], error) {
|
|
var out ListResult[T]
|
|
path := "/api/collections/" + url.PathEscape(collection) + "/records"
|
|
if q := opts.values().Encode(); q != "" {
|
|
path += "?" + q
|
|
}
|
|
err := c.Do(ctx, http.MethodGet, path, nil, &out)
|
|
return out, err
|
|
}
|
|
|
|
// Get fetches one record by id.
|
|
func Get[T any](ctx context.Context, c *Client, collection, id string) (T, error) {
|
|
return GetExpand[T](ctx, c, collection, id, "")
|
|
}
|
|
|
|
// GetExpand fetches one record by id with relations inlined.
|
|
func GetExpand[T any](ctx context.Context, c *Client, collection, id, expand string) (T, error) {
|
|
var out T
|
|
path := recordPath(collection, id)
|
|
if expand != "" {
|
|
path += "?expand=" + url.QueryEscape(expand)
|
|
}
|
|
err := c.Do(ctx, http.MethodGet, path, nil, &out)
|
|
return out, err
|
|
}
|
|
|
|
// Create inserts a record and returns the stored version.
|
|
func Create[T any](ctx context.Context, c *Client, collection string, body any) (T, error) {
|
|
var out T
|
|
err := c.Do(ctx, http.MethodPost, "/api/collections/"+url.PathEscape(collection)+"/records", body, &out)
|
|
return out, err
|
|
}
|
|
|
|
// Update patches a record and returns the stored version.
|
|
func Update[T any](ctx context.Context, c *Client, collection, id string, body any) (T, error) {
|
|
var out T
|
|
err := c.Do(ctx, http.MethodPatch, recordPath(collection, id), body, &out)
|
|
return out, err
|
|
}
|
|
|
|
// Delete removes a record.
|
|
func (c *Client) Delete(ctx context.Context, collection, id string) error {
|
|
return c.Do(ctx, http.MethodDelete, recordPath(collection, id), nil, nil)
|
|
}
|
|
|
|
func recordPath(collection, id string) string {
|
|
return "/api/collections/" + url.PathEscape(collection) + "/records/" + url.PathEscape(id)
|
|
}
|
|
|
|
// Do sends a JSON request as the superuser. On a 401 it re-authenticates once
|
|
// and retries.
|
|
func (c *Client) Do(ctx context.Context, method, path string, body, out any) error {
|
|
token, err := c.authToken(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err = c.send(ctx, method, path, token, body, out)
|
|
var pbErr *Error
|
|
if errors.As(err, &pbErr) && pbErr.Status == http.StatusUnauthorized {
|
|
c.mu.Lock()
|
|
if c.token == token {
|
|
c.token = ""
|
|
}
|
|
c.mu.Unlock()
|
|
if token, err = c.authToken(ctx); err != nil {
|
|
return err
|
|
}
|
|
err = c.send(ctx, method, path, token, body, out)
|
|
}
|
|
return err
|
|
}
|
|
|
|
// DoAs sends a JSON request on behalf of an end user: token is the user's
|
|
// auth token, or "" for an anonymous call (login, password reset, ...).
|
|
func (c *Client) DoAs(ctx context.Context, method, path, token string, body, out any) error {
|
|
return c.send(ctx, method, path, token, body, out)
|
|
}
|
|
|
|
func (c *Client) send(ctx context.Context, method, path, token string, body, out any) error {
|
|
var reader io.Reader
|
|
if body != nil {
|
|
buf, err := json.Marshal(body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
reader = bytes.NewReader(buf)
|
|
}
|
|
|
|
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reader)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if body != nil {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
if token != "" {
|
|
req.Header.Set("Authorization", token)
|
|
}
|
|
|
|
resp, err := c.http.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode >= 300 {
|
|
pbErr := &Error{Status: resp.StatusCode}
|
|
_ = json.NewDecoder(resp.Body).Decode(pbErr)
|
|
pbErr.Status = resp.StatusCode
|
|
return pbErr
|
|
}
|
|
if out == nil || resp.StatusCode == http.StatusNoContent {
|
|
return nil
|
|
}
|
|
return json.NewDecoder(resp.Body).Decode(out)
|
|
}
|
|
|
|
func (c *Client) authToken(ctx context.Context) (string, error) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if c.token != "" {
|
|
return c.token, nil
|
|
}
|
|
|
|
var res struct {
|
|
Token string `json:"token"`
|
|
}
|
|
err := c.send(ctx, http.MethodPost, "/api/collections/_superusers/auth-with-password", "",
|
|
map[string]string{"identity": c.email, "password": c.password}, &res)
|
|
if err != nil {
|
|
return "", fmt.Errorf("pocketbase superuser auth: %w", err)
|
|
}
|
|
c.token = res.Token
|
|
return c.token, nil
|
|
}
|