feat: exporter api, json exporter
This commit is contained in:
1 parent
4de3218c40
commit
92cb9267fc
3 files changed
+83
-6
No files matched your search
@@ -0,0 +1,43 @@
|
||||
package exporter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/abelith/spellbook/internal/models"
|
||||
"io"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Exporter interface {
|
||||
Export(ctx context.Context, ch <-chan models.Spell, w io.Writer) error
|
||||
}
|
||||
|
||||
var (
|
||||
exporters = make(map[string]Exporter)
|
||||
mu sync.Mutex
|
||||
)
|
||||
|
||||
func Register(name string, exp Exporter) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
if exp == nil {
|
||||
panic("exporter: Exporter cannot be nil")
|
||||
}
|
||||
if _, ok := exporters[name]; ok {
|
||||
panic("exporter: Register called twice for " + name)
|
||||
}
|
||||
exporters[name] = exp
|
||||
}
|
||||
|
||||
func Export(ctx context.Context, name string, ch <-chan models.Spell, w io.Writer) error {
|
||||
mu.Lock()
|
||||
exp, ok := exporters[name]
|
||||
mu.Unlock()
|
||||
|
||||
if !ok {
|
||||
return fmt.Errorf("exporter %s not found", name)
|
||||
}
|
||||
|
||||
return exp.Export(ctx, ch, w)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package json
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/abelith/spellbook/internal/adapters/exporter"
|
||||
"github.com/abelith/spellbook/internal/models"
|
||||
"io"
|
||||
)
|
||||
|
||||
func init() {
|
||||
exporter.Register("jsonl", &JsonlExporter{})
|
||||
}
|
||||
|
||||
type JsonlExporter 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,12 @@ import (
|
||||
)
|
||||
|
||||
type Spell struct {
|
||||
Id int
|
||||
Name string
|
||||
Spell string
|
||||
ShortDesc string
|
||||
Description string
|
||||
Tags []string
|
||||
Id int `json:"-"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Spell string `json:"spell,omitempty"`
|
||||
ShortDesc string `json:"short_desc,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
}
|
||||
|
||||
type SpellCast struct {
|
||||
|
||||
Reference in new issue
Block a user