5ca36b0502
Feature/listtypes * started * cleanuplist * someunittestfixes * removemostflakiness
63 lines
1.3 KiB
Go
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 *database.Connection
|
|
}
|
|
|
|
type Config struct {
|
|
Path string `json:"path"`
|
|
}
|
|
|
|
func NewExtractor(db *database.Connection) 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.Queries.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
|
|
}
|