-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAPI.go
111 lines (85 loc) · 2.29 KB
/
API.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
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
package api
import (
"reflect"
"github.com/aerogo/aero"
)
// API represents your application's API configuration.
type API struct {
// The base endpoint for all API requests.
root string
// The database used.
db Database
// An internal list of registered actions.
actions []*Action
}
// New creates a new API.
func New(root string, db Database) *API {
return &API{
root: root,
db: db,
}
}
// Install installs the REST & GraphQL API to your webserver at the given endpoint.
func (api *API) Install(app *aero.Application) {
for collection, typ := range api.db.Types() {
api.RegisterCollection(app, collection, typ)
}
for _, action := range api.actions {
route, handler := api.ActionHandler(action)
app.Post(route, handler)
}
}
// RegisterCollection registers a single collection.
func (api *API) RegisterCollection(app *aero.Application, collection string, objType reflect.Type) {
// Get
route, handler := api.Get(collection)
app.Get(route, handler)
// Get property
route, handler = api.GetField(collection)
app.Get(route, handler)
// Edit
route, handler = api.Edit(collection)
if route != "" && handler != nil {
app.Post(route, handler)
}
// Edit property
route, handler = api.EditField(collection)
if route != "" && handler != nil {
app.Post(route, handler)
}
// Delete
route, handler = api.Delete(collection)
if route != "" && handler != nil {
app.Post(route, handler)
}
// Append array element
route, handler = api.ArrayAppend(collection)
if route != "" && handler != nil {
app.Post(route, handler)
}
// Remove array element
route, handler = api.ArrayRemove(collection)
if route != "" && handler != nil {
app.Post(route, handler)
}
// Create
route, handler = api.Create(collection)
if route != "" && handler != nil {
app.Post(route, handler)
}
}
// RegisterAction registers an action for a collection.
func (api *API) RegisterAction(action *Action) {
api.actions = append(api.actions, action)
}
// RegisterActions registers actions for a collection.
func (api *API) RegisterActions(collection string, actions []*Action) {
for _, action := range actions {
action.Collection = collection
}
api.actions = append(api.actions, actions...)
}
// Type ...
func (api *API) Type(collection string) reflect.Type {
return api.db.Types()[collection]
}