github.com/iosif02/goja_nodejs@v1.0.1/console/module.go (about)

     1  package console
     2  
     3  import (
     4  	"github.com/iosif02/goja"
     5  	"github.com/iosif02/goja_nodejs/require"
     6  	"github.com/iosif02/goja_nodejs/util"
     7  )
     8  
     9  const ModuleName = "console"
    10  
    11  type Console struct {
    12  	runtime *goja.Runtime
    13  	util    *goja.Object
    14  	printer Printer
    15  }
    16  
    17  type Printer interface {
    18  	Log(string)
    19  	Warn(string)
    20  	Error(string)
    21  }
    22  
    23  func (c *Console) log(p func(string)) func(goja.FunctionCall) goja.Value {
    24  	return func(call goja.FunctionCall) goja.Value {
    25  		if format, ok := goja.AssertFunction(c.util.Get("format")); ok {
    26  			ret, err := format(c.util, call.Arguments...)
    27  			if err != nil {
    28  				panic(err)
    29  			}
    30  
    31  			p(ret.String())
    32  		} else {
    33  			panic(c.runtime.NewTypeError("util.format is not a function"))
    34  		}
    35  
    36  		return nil
    37  	}
    38  }
    39  
    40  func Require(runtime *goja.Runtime, module *goja.Object) {
    41  	requireWithPrinter(defaultStdPrinter)(runtime, module)
    42  }
    43  
    44  func RequireWithPrinter(printer Printer) require.ModuleLoader {
    45  	return requireWithPrinter(printer)
    46  }
    47  
    48  func requireWithPrinter(printer Printer) require.ModuleLoader {
    49  	return func(runtime *goja.Runtime, module *goja.Object) {
    50  		c := &Console{
    51  			runtime: runtime,
    52  			printer: printer,
    53  		}
    54  
    55  		c.util = require.Require(runtime, util.ModuleName).(*goja.Object)
    56  
    57  		o := module.Get("exports").(*goja.Object)
    58  		o.Set("log", c.log(c.printer.Log))
    59  		o.Set("error", c.log(c.printer.Error))
    60  		o.Set("warn", c.log(c.printer.Warn))
    61  		o.Set("info", c.log(c.printer.Log))
    62  		o.Set("debug", c.log(c.printer.Log))
    63  	}
    64  }
    65  
    66  func Enable(runtime *goja.Runtime) {
    67  	runtime.Set("console", require.Require(runtime, ModuleName))
    68  }
    69  
    70  func init() {
    71  	require.RegisterCoreModule(ModuleName, Require)
    72  }