forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsvm_event_handler.go
54 lines (43 loc) · 1.38 KB
/
jsvm_event_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"encoding/json"
"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/config"
)
const EH_JSVMHandler apidef.TykEventHandlerName = "eh_dynamic_handler"
type JSVMContextGlobal struct {
APIID string
OrgID string
}
// JSVMEventHandler is a scriptable event handler
type JSVMEventHandler struct {
methodName string
Spec *APISpec
SpecJSON string
}
// New enables the intitialisation of event handler instances when they are created on ApiSpec creation
func (l *JSVMEventHandler) Init(handlerConf interface{}) error {
l.methodName = handlerConf.(map[string]interface{})["name"].(string)
// Set the VM globals
globalVals := JSVMContextGlobal{
APIID: l.Spec.APIID,
OrgID: l.Spec.OrgID,
}
gValAsJSON, err := json.Marshal(globalVals)
if err != nil {
log.Error("Failed to marshal globals! ", err)
}
l.SpecJSON = string(gValAsJSON)
return nil
}
// HandleEvent will be fired when the event handler instance is found in an APISpec EventPaths object during a request chain
func (l *JSVMEventHandler) HandleEvent(em config.EventMessage) {
// JSON-encode the event data object
msgAsJSON, err := json.Marshal(em)
if err != nil {
log.Error("Failed to encode event data: ", err)
return
}
// Execute the method name with the JSON object
GlobalEventsJSVM.VM.Run(l.methodName + `.DoProcessEvent(` + string(msgAsJSON) + `,` + l.SpecJSON + `);`)
}