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