68 lines
1.2 KiB
Go
68 lines
1.2 KiB
Go
package json
|
|
|
|
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)
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
case spell, ok := <-ch:
|
|
if !ok {
|
|
return nil
|
|
}
|
|
|
|
if err := encoder.Encode(&spell); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|