diff --git a/pkg/generate/generator.go b/pkg/generate/generator.go new file mode 100644 index 000000000..52d041b4e --- /dev/null +++ b/pkg/generate/generator.go @@ -0,0 +1,42 @@ +package generate + +import ( + "github.com/dop251/goja" + "github.com/google/uuid" +) + +type Result struct { + Script string `json:"script"` + Variables map[string]string `json:"variables"` +} + +type Generator struct { + next func(int) Result +} + +func (g *Generator) Next(iteration int) Result { + return g.next(iteration) +} + +func NewGenerator(script string) (*Generator, error) { + runtime := goja.New() + _, err := runtime.RunString(script) + if err != nil { + return nil, err + } + runtime.SetFieldNameMapper(goja.TagFieldNameMapper("json", true)) + err = runtime.Set("uuid", uuid.NewString) + if err != nil { + return nil, err + } + + var next func(int) Result + err = runtime.ExportTo(runtime.Get("next"), &next) + if err != nil { + panic(err) + } + + return &Generator{ + next: next, + }, nil +} \ No newline at end of file diff --git a/test/performance/benchmark_test.go b/test/performance/benchmark_test.go index 114ab69f0..d816b796e 100644 --- a/test/performance/benchmark_test.go +++ b/test/performance/benchmark_test.go @@ -10,12 +10,12 @@ import ( ledgerclient "github.com/formancehq/ledger/pkg/client" "github.com/formancehq/ledger/pkg/client/models/components" "github.com/formancehq/ledger/pkg/client/models/operations" + "github.com/formancehq/ledger/pkg/generate" "net/http" "sort" "sync/atomic" "testing" - "github.com/dop251/goja" "github.com/formancehq/go-libs/v2/time" ledger "github.com/formancehq/ledger/internal" "github.com/google/uuid" @@ -43,30 +43,13 @@ func (fn TransactionProviderFactoryFn) Create() (TransactionProvider, error) { func NewJSTransactionProviderFactory(script string) TransactionProviderFactoryFn { return func() (TransactionProvider, error) { - runtime := goja.New() - _, err := runtime.RunString(script) + generator, err := generate.NewGenerator(script) if err != nil { return nil, err } - runtime.SetFieldNameMapper(goja.TagFieldNameMapper("json", true)) - err = runtime.Set("uuid", uuid.NewString) - if err != nil { - return nil, err - } - - type Result struct { - Script string `json:"script"` - Variables map[string]string `json:"variables"` - } - - var next func(int) Result - err = runtime.ExportTo(runtime.Get("next"), &next) - if err != nil { - panic(err) - } return TransactionProviderFn(func(iteration int) (string, map[string]string) { - ret := next(iteration) + ret := generator.Next(iteration) return ret.Script, ret.Variables }), nil }