1
0
mirror of https://github.com/StackExchange/dnscontrol.git synced 2024-05-11 05:55:12 +00:00

Adding simple require functionality to js (#58)

* Adding simple require functionality to js

* comment
This commit is contained in:
Craig Peterson
2017-03-27 16:01:12 -06:00
committed by GitHub
parent b0333f3244
commit efb8e9bbf4
5 changed files with 45 additions and 1 deletions

View File

@ -2,6 +2,8 @@ package js
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/StackExchange/dnscontrol/models"
@ -14,6 +16,8 @@ import (
func ExecuteJavascript(script string, devMode bool) (*models.DNSConfig, error) {
vm := otto.New()
vm.Set("require", require)
helperJs := GetHelpers(devMode)
// run helper script to prime vm and initialize variables
if _, err := vm.Run(helperJs); err != nil {
@ -44,3 +48,17 @@ func ExecuteJavascript(script string, devMode bool) (*models.DNSConfig, error) {
func GetHelpers(devMode bool) string {
return _escFSMustString(devMode, "/helpers.js")
}
func require(call otto.FunctionCall) otto.Value {
file := call.Argument(0).String()
fmt.Printf("requiring: %s\n", file)
data, err := ioutil.ReadFile(file)
if err != nil {
panic(err)
}
_, err = call.Otto.Run(string(data))
if err != nil {
panic(err)
}
return otto.TrueValue()
}