-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add generic function for from map
- Loading branch information
Parham Alvani
committed
Dec 28, 2023
1 parent
b2f60ac
commit 7691b45
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package fp | ||
|
||
import "encoding/json" | ||
|
||
func FromMap[T any](input map[string]any) (*T, error) { | ||
in, err := json.Marshal(input) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
out := new(T) | ||
if err := json.Unmarshal(in, out); err != nil { | ||
return nil, err | ||
} | ||
|
||
return out, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package fp_test | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/kaytu-io/kaytu-util/pkg/fp" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestFromMap(t *testing.T) { | ||
require := require.New(t) | ||
|
||
type student struct { | ||
Name string `json:"name,omitempty"` | ||
ID int `json:"id,omitempty"` | ||
} | ||
|
||
input := map[string]any{ | ||
"name": "Parham Alvani", | ||
"id": 9231058, | ||
} | ||
|
||
s, err := fp.FromMap[student](input) | ||
require.NoError(err) | ||
require.Equal("Parham Alvani", s.Name) | ||
require.Equal(9231058, s.ID) | ||
} |