-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdirectus.go
More file actions
336 lines (305 loc) · 7.92 KB
/
directus.go
File metadata and controls
336 lines (305 loc) · 7.92 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package directusapi
import (
"context"
"fmt"
"net/http"
"reflect"
"strings"
)
type PrimaryKey interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~string
}
// API is a generic API client for any Directus collection
// R is a read model
// W is a write model
// PK is a type of primary key
type API[R, W any, PK PrimaryKey] struct {
Scheme string
Host string
Namespace string
CollectionName string
BearerToken string
HTTPClient *http.Client
queryFields []string
debug bool
}
// CreateToken uses provided credentials to generate server token
//
// Related Directus reference:
// https://v8.docs.directus.io/api/authentication.html#retrieve-a-temporary-access-token
func (d API[R, W, PK]) CreateToken(ctx context.Context, email, password string) (string, error) {
u := fmt.Sprintf("%s://%s/%s/auth/authenticate", d.Scheme, d.Host, d.Namespace)
body := struct {
Email string `json:"email"`
Password string `json:"password"`
}{
email,
password,
}
req := request{
ctx,
http.MethodPost,
u,
nil,
body,
}
var respBody struct {
Data struct {
Token string `json:"token"`
} `json:"data"`
}
err := d.executeRequest(req, http.StatusOK, &respBody)
if err != nil {
return "", fmt.Errorf("execute create token request: %w", err)
}
return respBody.Data.Token, nil
}
// Insert attempts to insert new item
//
// Related Directus reference:
// https://v8.docs.directus.io/api/items.html#create-an-item
func (d API[R, W, PK]) Insert(ctx context.Context, item W) (R, error) {
var empty R
u := fmt.Sprintf("%s://%s/%s/items/%s", d.Scheme, d.Host, d.Namespace, d.CollectionName)
req := request{
ctx,
http.MethodPost,
u,
map[string]string{
"fields": strings.Join(d.jsonFieldsR(), ","),
},
item,
}
var respBody struct {
Data R `json:"data"`
}
err := d.executeRequest(req, http.StatusOK, &respBody)
if err != nil {
return empty, fmt.Errorf("execute insert request: %w", err)
}
return respBody.Data, nil
}
// Create attempts to create new item with partials
//
// Related Directus reference:
// https://v8.docs.directus.io/api/items.html#create-an-item
func (d API[R, W, PK]) Create(ctx context.Context, partials map[string]any) (R, error) {
var empty R
u := fmt.Sprintf("%s://%s/%s/items/%s", d.Scheme, d.Host, d.Namespace, d.CollectionName)
req := request{
ctx,
http.MethodPost,
u,
map[string]string{
"fields": strings.Join(d.jsonFieldsR(), ","),
},
partials,
}
var respBody struct {
Data R `json:"data"`
}
err := d.executeRequest(req, http.StatusOK, &respBody)
if err != nil {
return empty, fmt.Errorf("execute create request: %w", err)
}
return respBody.Data, nil
}
// GetByID reads a single item by given ID
//
// Related Directus reference:
// https://v8.docs.directus.io/api/items.html#retrieve-an-item
func (d API[R, W, PK]) GetByID(ctx context.Context, id PK) (R, error) {
u := fmt.Sprintf("%s://%s/%s/items/%s/%v", d.Scheme, d.Host, d.Namespace, d.CollectionName, id)
req := request{
ctx,
http.MethodGet,
u,
map[string]string{
"fields": strings.Join(d.jsonFieldsR(), ","),
},
nil,
}
var respBody struct {
Data R `json:"data"`
}
var empty R
err := d.executeRequest(req, http.StatusOK, &respBody)
if err != nil {
return empty, fmt.Errorf("execute get by id request: %w", err)
}
return respBody.Data, nil
}
// Update performs partial update of an item with given id
//
// Related Directus reference:
// https://v8.docs.directus.io/api/items.html#update-an-item
func (d API[R, W, PK]) Update(ctx context.Context, id PK, partials map[string]any) (R, error) {
var empty R
u := fmt.Sprintf("%s://%s/%s/items/%s/%v", d.Scheme, d.Host, d.Namespace, d.CollectionName, id)
req := request{
ctx,
http.MethodPatch,
u,
map[string]string{
"fields": strings.Join(d.jsonFieldsR(), ","),
},
partials,
}
var respBody struct {
Data R `json:"data"`
}
err := d.executeRequest(req, http.StatusOK, &respBody)
if err != nil {
return empty, fmt.Errorf("execute update request: %w", err)
}
return respBody.Data, nil
}
// Set performs an update of an item with given id
//
// Related Directus reference:
// https://v8.docs.directus.io/api/items.html#update-an-item
func (d API[R, W, PK]) Set(ctx context.Context, id PK, item W) (R, error) {
var empty R
u := fmt.Sprintf("%s://%s/%s/items/%s/%v", d.Scheme, d.Host, d.Namespace, d.CollectionName, id)
req := request{
ctx,
http.MethodPatch,
u,
map[string]string{
"fields": strings.Join(d.jsonFieldsR(), ","),
},
item,
}
var respBody struct {
Data R `json:"data"`
}
err := d.executeRequest(req, http.StatusOK, &respBody)
if err != nil {
return empty, fmt.Errorf("execute set request: %w", err)
}
return respBody.Data, nil
}
// Delete removes item with a given id
//
// Related Directus reference:
// https://v8.docs.directus.io/api/items.html#update-an-item
func (d API[R, W, PK]) Delete(ctx context.Context, id PK) error {
u := fmt.Sprintf("%s://%s/%s/items/%s/%v", d.Scheme, d.Host, d.Namespace, d.CollectionName, id)
req := request{
ctx,
http.MethodDelete,
u,
nil,
nil,
}
err := d.executeRequest(req, http.StatusNoContent, nil)
if err != nil {
return fmt.Errorf("execute delete request: %w", err)
}
return nil
}
// Items retrieves a collection of items
//
// Related Directus reference:
// https://v8.docs.directus.io/api/items.html#update-an-item
func (d API[R, W, PK]) Items(ctx context.Context, q query) ([]R, error) {
u := fmt.Sprintf("%s://%s/%s/items/%s", d.Scheme, d.Host, d.Namespace, d.CollectionName)
qv := q.asKeyValue()
qv["fields"] = strings.Join(d.jsonFieldsR(), ",")
req := request{
ctx,
http.MethodGet,
u,
qv,
nil,
}
var respBody struct {
Data []R `json:"data"`
}
err := d.executeRequest(req, http.StatusOK, &respBody)
if err != nil {
return nil, fmt.Errorf("execute items request: %w", err)
}
return respBody.Data, nil
}
func (d *API[R, W, PK]) jsonFieldsR() []string {
if d.queryFields == nil {
var x R
t := reflect.TypeOf(x)
d.queryFields = iterateFields(t, "")
}
return d.queryFields
}
// iterateFields returns fields for all struct's fields
func iterateFields(t reflect.Type, prefix string) []string {
fields := []string{}
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
fields = append(fields, structFields(f, prefix)...)
}
return fields
}
// structFields returns fields for a signle struct field
func structFields(f reflect.StructField, prefix string) []string {
tagVal := ""
if v, ok := f.Tag.Lookup(tagName); ok {
tagVal = v
} else {
tagVal = f.Name
}
switch f.Type.Kind() {
case reflect.Struct:
var t Time
isTime := f.Type.ConvertibleTo(reflect.TypeOf(t))
isOptional := f.Type.Implements(reflect.TypeOf(new(isOpt)).Elem())
switch {
case isOptional:
val := reflect.New(f.Type).Interface().(isOpt)
if prefix == "" {
return val.fields(tagVal)
} else {
return val.fields(prefix + "." + tagVal)
}
case isTime:
return []string{prefix}
default:
p := prefix
if p != "" {
p = p + "." + tagVal
} else {
p = tagVal
}
return iterateFields(f.Type, p)
}
case reflect.Slice:
p := prefix
if p != "" {
p = p + "." + tagVal
} else {
p = tagVal
}
if f.Type.Elem().Kind() == reflect.Struct {
return iterateFields(f.Type.Elem(), p)
}
return []string{p}
case
reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64,
reflect.String, reflect.Map:
// field is not nested
v := tagVal
if prefix != "" {
v = prefix + "." + tagVal
}
return []string{v}
case reflect.Pointer:
t := f.Type.Elem().String()
panic(f.Name + "(" + t + "," + prefix + "): pointer is not supported, use directus.Optional instead")
default:
panic(f.Type.Kind().String() + " not implemented")
}
}
type isOpt interface {
getOp() operation
fields(prefix string) []string
}