-
Notifications
You must be signed in to change notification settings - Fork 0
/
props.go
97 lines (81 loc) · 2.14 KB
/
props.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
package inertia
import (
"fmt"
"net/http"
"strings"
)
// LazyProp is a property value that will only evaluate when needed.
//
// https://inertiajs.com/partial-reloads
type LazyProp func() (any, error)
func (i *Inertia) PrepareProps(r *http.Request, component string, props Props) (Props, error) {
result := make(Props)
// Add shared props to the result.
for key, val := range i.SharedProps {
result[key] = val
}
// Add props from context to the result.
contextProps := r.Context().Value(ContextKeyProps)
if contextProps != nil {
contextProps, ok := contextProps.(Props)
if !ok {
return nil, ErrInvalidContextProps
}
for key, value := range contextProps {
result[key] = value
}
}
// Add passed props to the result.
for key, val := range props {
result[key] = val
}
// Get props keys to return. If len == 0, then return all.
partial := r.Header.Get("X-Inertia-Partial-Data")
data := strings.Split(partial, ",")
only := make(map[string]struct{}, len(data))
if partial != "" && r.Header.Get("X-Inertia-Partial-Component") == component {
for _, value := range data {
only[value] = struct{}{}
}
}
// Filter props.
if len(only) > 0 {
// While making partial requests:
// Use the `only` property to specify which data the server should return.
for key := range result {
if _, ok := only[key]; !ok {
delete(result, key)
}
}
} else {
// Lazy props should only be evaluated when required using the `only` property
for key, val := range result {
if _, ok := val.(LazyProp); ok {
delete(result, key)
}
}
}
// Resolve props values.
for key, val := range result {
val, err := ResolvePropVal(val)
if err != nil {
return nil, fmt.Errorf("resolve prop value: %w", err)
}
result[key] = val
}
return result, nil
}
func ResolvePropVal(val any) (any, error) {
var err error
if closure, ok := val.(func() (any, error)); ok {
if val, err = closure(); err != nil {
return nil, fmt.Errorf("closure prop resolving: %w", err)
}
} else if lazy, ok := val.(LazyProp); ok {
val, err = lazy()
if err != nil {
return nil, fmt.Errorf("lazy prop resolving: %w", err)
}
}
return val, nil
}