edge/pkg/module/context.go

56 lines
1.0 KiB
Go
Raw Normal View History

2023-02-09 12:16:36 +01:00
package module
import (
"context"
"sync"
"forge.cadoles.com/arcad/edge/pkg/app"
"github.com/dop251/goja"
"github.com/pkg/errors"
)
func assertContext(v goja.Value, r *goja.Runtime) context.Context {
if c, ok := v.Export().(context.Context); ok {
return c
}
panic(r.NewTypeError("value should be a context"))
}
type ContextModule struct {
ctx BackendContext
mutex sync.RWMutex
}
func (m *ContextModule) Name() string {
return "context"
}
func (m *ContextModule) get(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
m.mutex.RLock()
defer m.mutex.RUnlock()
return rt.ToValue(m.ctx)
}
func (m *ContextModule) Export(export *goja.Object) {
if err := export.Set("get", m.get); err != nil {
panic(errors.Wrap(err, "could not set 'get' function"))
}
}
func ContextModuleFactory() app.BackendModuleFactory {
return func(backend *app.Backend) app.BackendModule {
return &ContextModule{
ctx: BackendContext{
Context: context.Background(),
},
mutex: sync.RWMutex{},
}
}
}
type BackendContext struct {
context.Context
}