-
Notifications
You must be signed in to change notification settings - Fork 31
/
collection.go
66 lines (52 loc) · 1.51 KB
/
collection.go
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
package pocketbase
import (
"encoding/json"
"fmt"
)
type Collection[T any] struct {
*Client
Name string
}
func CollectionSet[T any](client *Client, collection string) Collection[T] {
return Collection[T]{client, collection}
}
func (c Collection[T]) Update(id string, body T) error {
return c.Client.Update(c.Name, id, body)
}
func (c Collection[T]) Create(body T) (ResponseCreate, error) {
return c.Client.Create(c.Name, body)
}
func (c Collection[T]) Delete(id string) error {
return c.Client.Delete(c.Name, id)
}
func (c Collection[T]) List(params ParamsList) (ResponseList[T], error) {
var response ResponseList[T]
params.hackResponseRef = &response
_, err := c.Client.List(c.Name, params)
return response, err
}
func (c Collection[T]) One(id string) (T, error) {
var response T
if err := c.Authorize(); err != nil {
return response, err
}
request := c.client.R().
SetHeader("Content-Type", "application/json").
SetPathParam("collection", c.Name).
SetPathParam("id", id)
resp, err := request.Get(c.url + "/api/collections/{collection}/records/{id}")
if err != nil {
return response, fmt.Errorf("[one] can't send update request to pocketbase, err %w", err)
}
if resp.IsError() {
return response, fmt.Errorf("[one] pocketbase returned status: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
if err := json.Unmarshal(resp.Body(), &response); err != nil {
return response, fmt.Errorf("[one] can't unmarshal response, err %w", err)
}
return response, nil
}