-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Vincent Boutour <[email protected]>
- Loading branch information
Showing
4 changed files
with
51 additions
and
175 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
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,49 @@ | ||
package provider | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"errors" | ||
"fmt" | ||
"io" | ||
|
||
absto "github.com/ViBiOh/absto/pkg/model" | ||
) | ||
|
||
func LoadJSON[T any](ctx context.Context, storageApp absto.Storage, filename string) (output T, err error) { | ||
var reader io.ReadCloser | ||
|
||
reader, err = storageApp.ReadFrom(ctx, filename) | ||
if err != nil { | ||
err = fmt.Errorf("read: %w", err) | ||
return | ||
} | ||
|
||
defer func() { | ||
err = errors.Join(err, reader.Close()) | ||
}() | ||
|
||
if err = json.NewDecoder(reader).Decode(&output); err != nil { | ||
err = fmt.Errorf("decode: %w", storageApp.ConvertError(err)) | ||
} | ||
|
||
return | ||
} | ||
|
||
func SaveJSON[T any](ctx context.Context, storageApp absto.Storage, filename string, content T) error { | ||
reader, writer := io.Pipe() | ||
|
||
done := make(chan error) | ||
go func() { | ||
defer close(done) | ||
var err error | ||
|
||
if jsonErr := json.NewEncoder(writer).Encode(content); jsonErr != nil { | ||
err = fmt.Errorf("encode: %w", jsonErr) | ||
} | ||
|
||
done <- errors.Join(err, writer.Close()) | ||
}() | ||
|
||
return errors.Join(storageApp.WriteTo(ctx, filename, reader, absto.WriteOpts{}), <-done) | ||
} |
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
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