feat: json importer
This commit is contained in:
1 parent
69af7eaee3
commit
c41d13bb77
3 files changed
+40
No files matched your search
@@ -4,16 +4,20 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/abelith/spellbook/internal/adapters/exporter"
|
||||
"github.com/abelith/spellbook/internal/adapters/importer"
|
||||
"github.com/abelith/spellbook/internal/models"
|
||||
"io"
|
||||
)
|
||||
|
||||
func init() {
|
||||
exporter.Register("jsonl", &JsonlExporter{})
|
||||
importer.Register("jsonl", &JsonlImporter{})
|
||||
}
|
||||
|
||||
type JsonlExporter struct{}
|
||||
|
||||
type JsonlImporter struct{}
|
||||
|
||||
func (je *JsonlExporter) Export(ctx context.Context, ch <-chan models.Spell, w io.Writer) error {
|
||||
encoder := json.NewEncoder(w)
|
||||
|
||||
@@ -32,3 +36,32 @@ func (je *JsonlExporter) Export(ctx context.Context, ch <-chan models.Spell, w i
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ji JsonlImporter) Import(ctx context.Context, r io.Reader) (<-chan models.Spell, <-chan error, error) {
|
||||
ch := make(chan models.Spell, 1)
|
||||
errCh := make(chan error, 1)
|
||||
|
||||
dec := json.NewDecoder(r)
|
||||
|
||||
go func() {
|
||||
defer close(ch)
|
||||
defer close(errCh)
|
||||
|
||||
for dec.More() {
|
||||
var spell models.Spell
|
||||
if err := dec.Decode(&spell); err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
errCh <- ctx.Err()
|
||||
return
|
||||
case ch <- spell:
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return ch, errCh, nil
|
||||
}
|
||||
@@ -100,12 +100,17 @@ func (a *Application) ImportSpells(
|
||||
name string,
|
||||
r io.Reader,
|
||||
) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
ch, errCh, err := importer.Import(ctx, name, r)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return err
|
||||
}
|
||||
|
||||
if err := a.spellCmd.Import(ctx, ch); err != nil {
|
||||
cancel()
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ var reservedCommands = map[string]struct{}{
|
||||
"help": {},
|
||||
"completion": {},
|
||||
"search": {},
|
||||
"export": {},
|
||||
"import": {},
|
||||
}
|
||||
|
||||
func NewAddCommand(app Application) *cobra.Command {
|
||||
|
||||
Reference in new issue
Block a user