60 lines
1.2 KiB
Go
60 lines
1.2 KiB
Go
package jsonextractor
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"gotemplate/internal/database"
|
|
"gotemplate/internal/database/repository"
|
|
"gotemplate/internal/query"
|
|
"gotemplate/internal/result"
|
|
|
|
"github.com/tidwall/gjson"
|
|
)
|
|
|
|
type Extractor struct {
|
|
db *repository.Queries
|
|
}
|
|
|
|
type Config struct {
|
|
Path string `json:"path"`
|
|
}
|
|
|
|
func New(db *repository.Queries) *Extractor {
|
|
return &Extractor{db}
|
|
}
|
|
|
|
func (e *Extractor) Process(ctx context.Context, query query.Query, values *[]result.Value) (string, error) {
|
|
if len(*values) != 1 {
|
|
return "", fmt.Errorf("JSON Extraction requires 1 result")
|
|
}
|
|
|
|
value := (*values)[0].Value
|
|
|
|
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
|
|
}
|