Files
query-orchestration/internal/jsonExtractor/service.go
T

63 lines
1.3 KiB
Go
Raw Normal View History

2024-12-20 17:54:05 +00:00
package jsonextractor
2024-12-23 12:26:05 +00:00
import (
"context"
"encoding/json"
"fmt"
2024-12-24 17:13:48 +00:00
"queryorchestration/internal/database"
"queryorchestration/internal/database/repository"
2025-01-03 13:41:07 +00:00
queryprocessor "queryorchestration/internal/queryProcessor"
2024-12-24 17:13:48 +00:00
"queryorchestration/internal/result"
2024-12-20 17:54:05 +00:00
2024-12-23 12:26:05 +00:00
"github.com/tidwall/gjson"
)
type Extractor struct {
2025-01-06 12:26:28 +00:00
db *database.Connection
2024-12-23 12:26:05 +00:00
}
type Config struct {
Path string `json:"path"`
}
2025-01-06 12:26:28 +00:00
func NewExtractor(db *database.Connection) Extractor {
2025-01-03 13:41:07 +00:00
return Extractor{db}
2024-12-23 12:26:05 +00:00
}
2025-01-03 13:41:07 +00:00
func (e Extractor) Process(ctx context.Context, query queryprocessor.Query, values *[]result.Value) (string, error) {
2024-12-23 12:26:05 +00:00
if len(*values) != 1 {
return "", fmt.Errorf("JSON Extraction requires 1 result")
}
2024-12-24 17:13:48 +00:00
value, err := (*values)[0].GetValue(ctx)
if err != nil {
return "", err
}
2024-12-23 12:26:05 +00:00
2025-01-06 12:26:28 +00:00
byteConfig, err := e.db.Queries.GetQueryConfig(ctx, repository.GetQueryConfigParams{
2024-12-24 12:47:40 +00:00
Queryid: database.MustToDBUUID(query.ID),
Addedversion: query.Version,
2024-12-23 12:26:05 +00:00
})
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
2024-12-20 17:54:05 +00:00
}