-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathrelated_apis.go
66 lines (52 loc) · 1.47 KB
/
related_apis.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 babyapi
import (
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
)
// RelatedAPI declares a subset of methods from the API struct that are required to enable
// nested/parent-child API relationships
type RelatedAPI interface {
Router() (chi.Router, error)
Route(chi.Router) error
Base() string
Name() string
GetIDParam(*http.Request) string
Parent() RelatedAPI
CreateClientMap(*Client[*AnyResource]) map[string]*Client[*AnyResource]
}
type relatedAPI interface {
RelatedAPI
setParent(relatedAPI)
getCustomResponseCodeMap() map[string]int
isRoot() bool
}
// Parent returns the API's parent API
func (a *API[T]) Parent() RelatedAPI {
return a.parent
}
// GetParentIDParam reads the URL param from the request to get the ID of the parent resource
func (a *API[T]) GetParentIDParam(r *http.Request) string {
return a.parent.GetIDParam(r)
}
// AddNestedAPI adds a child API to this API and initializes the parent relationship on the child's side
func (a *API[T]) AddNestedAPI(childAPI RelatedAPI) *API[T] {
a.panicIfReadOnly()
relAPI, ok := childAPI.(relatedAPI)
if !ok {
a.errors = append(a.errors, fmt.Errorf("AddNestedAPI: incompatible type for child API: %T", childAPI))
return a
}
a.subAPIs[childAPI.Name()] = relAPI
relAPI.setParent(a)
return a
}
func (a *API[T]) setParent(parent relatedAPI) {
a.parent = parent
}
func (a *API[T]) getCustomResponseCodeMap() map[string]int {
return a.responseCodes
}
func (a *API[T]) isRoot() bool {
return a.rootAPI
}