-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelpers.go
53 lines (43 loc) · 1.6 KB
/
helpers.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
package nocodbgo
import (
"encoding/json"
"fmt"
)
// decodeInto converts data from a map or slice of maps into the provided destination struct or slice of structs.
// It uses JSON marshaling and unmarshaling internally to perform the conversion.
func decodeInto(data any, dest any) error {
jsonData, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("failed to marshal data: %w", err)
}
if err := json.Unmarshal(jsonData, dest); err != nil {
return fmt.Errorf("failed to unmarshal data: %w", err)
}
return nil
}
// structToMap converts a struct into a map[string]any using the struct's JSON tags.
// This is useful when you need to convert a strongly typed struct into a map for API operations.
func structToMap(data any) (map[string]any, error) {
jsonData, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("failed to marshal struct: %w", err)
}
var result map[string]any
if err := json.Unmarshal(jsonData, &result); err != nil {
return nil, fmt.Errorf("failed to unmarshal into map: %w", err)
}
return result, nil
}
// structsToMaps converts a slice of structs into a slice of maps using JSON tags.
// This is useful when you need to convert a slice of strongly typed structs into a slice of maps for API operations.
func structsToMaps(data any) ([]map[string]any, error) {
jsonData, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("failed to marshal structs: %w", err)
}
var result []map[string]any
if err := json.Unmarshal(jsonData, &result); err != nil {
return nil, fmt.Errorf("failed to unmarshal into maps: %w", err)
}
return result, nil
}