Skip to content

Commit

Permalink
feat: introduce generate package
Browse files Browse the repository at this point in the history
  • Loading branch information
gfyrag committed Oct 25, 2024
1 parent d328f65 commit e9d6d6c
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 20 deletions.
42 changes: 42 additions & 0 deletions pkg/generate/generator.go
Original file line number Diff line number Diff line change
@@ -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
}
23 changes: 3 additions & 20 deletions test/performance/benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}
Expand Down

0 comments on commit e9d6d6c

Please sign in to comment.