Permalink
Browse files

added javascript interpreter

  • Loading branch information...
alash3al committed Jan 9, 2019
1 parent c6083f2 commit 9a7069588e7eaff063b954014ea355372a2607c4
Showing with 41 additions and 20 deletions.
  1. +17 −15 api.example.hcl
  2. +22 −3 macro.go
  3. +1 −1 routes.go
  4. +1 −1 server_resp.go
@@ -66,21 +66,23 @@ adduser {
SQL
}

proclist {
exec = "SHOW PROCESSLIST"
}

tables {
exec = "SELECT * FROM information_schema.tables"
}

// list all databases, and run a transformer function
databases {
exec = "SHOW DATABASES"
}

users {
exec = <<SQL
select name, count(*) from users
group by name;
SQL
}
transformer = <<JS
// there is a global variable called `$result`,
// `$result` holds the result of the sql execution.
(function(){
throw 'aaa'
return ""
newResult = []
for ( i in $result ) {
newResult.push($result[i].Database)
}
return newResult
})()
JS
}
@@ -10,6 +10,7 @@ import (
"strings"
"text/template"

"github.com/dop251/goja"
"github.com/jmoiron/sqlx"
)

@@ -19,6 +20,7 @@ type Macro struct {
Methods []string `json:"method"`
Rules map[string][]string `json:"rules"`
Exec string `json:"exec"`
Transformer string `json:"transformer"`
name string
compiled *template.Template
}
@@ -36,10 +38,15 @@ func (m *Macro) Call(input map[string]interface{}) (interface{}, error) {

src, err := m.compileMacro(ctx)
if err != nil {
return nil, err
return err.Error(), err
}

out, err := m.execSQLQuery(strings.Split(src, ";"), ctx.SQLArgs)
if err != nil {
return err.Error(), err
}

return m.execSQLQuery(strings.Split(src, ";"), ctx.SQLArgs)
return m.execTransformer(out, m.Transformer)
}

// compileMacro - compile the specified macro and pass the specified ctx
@@ -135,4 +142,16 @@ func (m *Macro) scanSQLRow(rows *sqlx.Rows) (map[string]interface{}, error) {
return row, nil
}

// func (m *Macro) execJS()
// execTransformer - run the transformer function
func (m *Macro) execTransformer(data interface{}, transformer string) (interface{}, error) {
vm := goja.New()

vm.Set("$result", data)

v, err := vm.RunString(transformer)
if err != nil {
return nil, err
}

return v, nil
}
@@ -35,7 +35,7 @@ func routeExecMacro(c echo.Context) error {
if err != nil {
return c.JSON(500, map[string]interface{}{
"success": false,
"error": out,
"error": err.Error(),
})
}

@@ -92,7 +92,7 @@ func commandExecMacro(conn redcon.Conn, macro *Macro, input map[string]interface
conn.WriteArray(2)
conn.WriteInt(0)

j, _ := json.Marshal(out)
j, _ := json.Marshal(err.Error())

conn.WriteBulk(j)

0 comments on commit 9a70695

Please sign in to comment.