Files
query-orchestration/internal/jsonExtractor/service.go
T
Michael McGuinness 788b21594c creatorupdatordeprecate
2025-01-07 13:54:41 +00:00

63 lines
1.3 KiB
Go

package jsonextractor
import (
"context"
"encoding/json"
"fmt"
"queryorchestration/internal/database"
"queryorchestration/internal/database/repository"
queryprocessor "queryorchestration/internal/queryProcessor"
"queryorchestration/internal/result"
"github.com/tidwall/gjson"
)
type Extractor struct {
db *repository.Queries
}
type Config struct {
Path string `json:"path"`
}
func NewExtractor(db *repository.Queries) Extractor {
return Extractor{db}
}
func (e Extractor) Process(ctx context.Context, query queryprocessor.Query, values *[]result.Value) (string, error) {
if len(*values) != 1 {
return "", fmt.Errorf("JSON Extraction requires 1 result")
}
value, err := (*values)[0].GetValue(ctx)
if err != nil {
return "", err
}
byteConfig, err := e.db.GetQueryConfig(ctx, repository.GetQueryConfigParams{
Queryid: database.MustToDBUUID(query.ID),
Addedversion: query.Version,
})
if err != nil {
return "", err
}
var config Config
err = json.Unmarshal(byteConfig.Config, &config)
if err != nil {
return "", err
}
return e.extract(value, config.Path)
}
func (e *Extractor) extract(jsonString string, path string) (string, error) {
value := gjson.Get(jsonString, path)
if !value.Exists() {
return "", fmt.Errorf("JSON path does not exist: %s", path)
}
return value.String(), nil
}