Skip to content

Commit

Permalink
add ability to instantiate the json provider from fs interface
Browse files Browse the repository at this point in the history
  • Loading branch information
darklam committed Apr 3, 2024
1 parent cf2fbbc commit 16b40f7
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
26 changes: 25 additions & 1 deletion providers/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ package providers
import (
"errors"
"fmt"
json "github.com/titanous/json5"
"io"
"io/fs"
"os"

json "github.com/titanous/json5"
)

type JSONProvider struct {
Expand All @@ -27,6 +30,27 @@ func NewJSONProvider(filePath string) (*JSONProvider, error) {
return &JSONProvider{parsedFile: parsed}, nil
}

func NewJSONProviderFromFs(fs fs.FS, filePath string) (*JSONProvider, error) {
file, err := fs.Open(filePath)
if err != nil {
return nil, err
}

contents, err := io.ReadAll(file)
if err != nil {
return nil, err
}

parsed := map[string]interface{}{}

err = json.Unmarshal(contents, &parsed)
if err != nil {
return nil, err
}

return &JSONProvider{parsedFile: parsed}, nil
}

func (jp JSONProvider) GetValue(fieldPath []string) (string, error) {
var currentValue interface{} = jp.parsedFile

Expand Down
17 changes: 17 additions & 0 deletions providers/json_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package providers

import (
"embed"
"errors"
"fmt"
"os"
Expand Down Expand Up @@ -81,3 +82,19 @@ func TestJSONProvider_GetValue(t *testing.T) {
})
}
}

//go:embed test.config.json5
var config embed.FS

func TestNewJSONProviderFromFs(t *testing.T) {
jp, err := NewJSONProviderFromFs(config, "test.config.json5")
assert.Nil(t, err)

value, err := jp.GetValue([]string{"some"})
assert.Nil(t, err)
assert.Equal(t, "value", value)

value, err = jp.GetValue([]string{"nested", "key"})
assert.Nil(t, err)
assert.Equal(t, "value", value)
}
6 changes: 6 additions & 0 deletions providers/test.config.json5
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
some: "value",
nested: {
key: "value",
},
}

0 comments on commit 16b40f7

Please sign in to comment.