Skip to content

Instantly share code, notes, and snippets.

@letzya
Last active July 27, 2018 14:00
Show Gist options
  • Save letzya/2a77c7bd1a176c5d9a82c85d0ac8a87e to your computer and use it in GitHub Desktop.
Save letzya/2a77c7bd1a176c5d9a82c85d0ac8a87e to your computer and use it in GitHub Desktop.
Virtual Endpoint Example

Demo for Virtual Endpoints

This demo requires an on-premises installation of tyk-pro

You can quickly import the API definition TykDefidefinitionVirtualEndpoint.json into dashboard as a new api and test it with the following api call:

curl --url 'http://tyk-gateway:8080/testvirtualendpoint2/headers?param1=I-am-param-1' --header 'location: /get' -v or you can set it up your self by following the instruction bellow:

Setting up virtual endpoint

  1. Go to Enpoint Designer
  2. Add an endpoint
  3. On the plugin list check Virtual Endpoint
  4. Function name: Choos a unique name in "JS function to call:" and use it again inside the code fas the function name
  5. Paste this function in the editor code pace:

Note: Every line in the script gives an example of a functionality usage:

  • How to get form param
  • How to get specific key inside json variable
  • The structure of request object with Body, Headers, (need to add session object examples)
  • Using TykMakeHttpRequest, and the json it returns - .Code and .Body
function myVirtualHandlerGetHeaders (request, session, config) {
    rawlog("Virtual Test running")
    
    //Usage examples:
    log("Request Session: " + JSON.stringify(session))
    log("API Config:" + JSON.stringify(config))
 
    log("Request object: " + JSON.stringify(request))   
    log("Request Body: " + JSON.stringify(request.Body))
    log("Request Headers:"+ JSON.stringify(request.Headers))
    log("param-1:"+ request.Params["param1"])
    
    log("Request header type:" + typeof JSON.stringify(request.Headers))
    log("Request header:" + JSON.stringify(request.Headers.Location))
    

    //Make api call to upstream target
    newRequest = {
        "Method": "GET",
        "Body": "",
        "Headers": {"location":JSON.stringify(request.Headers.Location)},
        "Domain": "http://httpbin.org",
        "Resource": "/headers",
        "FormData": {}
    };
    rawlog("--- before get to upstream ---")
    response = TykMakeHttpRequest(JSON.stringify(newRequest));
    rawlog("--- After get to upstream ---")
    log('response type: ' + typeof response);
    log('response: ' + response);
    usableResponse = JSON.parse(response);
    var bodyObject = JSON.parse(usableResponse.Body);
    
    var responseObject = {
        //Body: "THIS IS A  VIRTUAL RESPONSE",
        Body: "yo yo",
        Headers: {
            "test": "virtual",
            "test-2": "virtual",
            "location" : bodyObject.headers.Location
        },
        Code: usableResponse.Code
    }
    
    rawlog("Virtual Test ended")
    return TykJsResponse(responseObject, session.meta_data)   
}

Notes:


Demonstrate the virtual endpoint:

yaara@Yaara's Mac ~/work/sso/localhost_env $ curl --url 'http://tyk-gateway:8080/testvirtualendpoint2/headers?param1=I-am-param-1'   --header 'location: /get' -v
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to tyk-gateway (127.0.0.1) port 8080 (#0)
> GET /testvirtualendpoint2/headers?param1=I-am-param-1 HTTP/1.1
> Host: tyk-gateway:8080
> User-Agent: curl/7.54.0
> Accept: */*
> location: /get
>
< HTTP/1.1 200 OK
< Date: Wed, 13 Jun 2018 13:45:22 GMT
< Location: /get
< Server: tyk
< Test: virtual
< Test-2: virtual
< X-Ratelimit-Limit: 0
< X-Ratelimit-Remaining: 0
< X-Ratelimit-Reset: 0
< Content-Length: 5
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host tyk-gateway left intact
yo yo

Gateway's log

[Jun 13 14:45:21] DEBUG jsvm: Running: myVirtualHandlerGetHeaders
Virtual Test running
[Jun 13 14:45:21]  INFO jsvm-logmsg: Request Session: {"access_rights":null,"alias":"","allowance":0,"apply_policies":null,"apply_policy_id":"","basic_auth_data":{"hash_type":"","password":""},"certificate":"","data_expires":0,"enable_detail_recording":false,"expires":0,"hmac_enabled":false,"hmac_string":"","id_extractor_deadline":0,"is_inactive":false,"jwt_data":{"secret":""},"last_check":0,"last_updated":"","meta_data":null,"monitor":{"trigger_limits":null},"oauth_client_id":"","oauth_keys":null,"org_id":"","per":0,"quota_max":0,"quota_remaining":0,"quota_renewal_rate":0,"quota_renews":0,"rate":0,"session_lifetime":0,"tags":null} type=log-msg
[Jun 13 14:45:21]  INFO jsvm-logmsg: API Config:{"APIID":"57d72796c5de45e649f22da390d7df43","OrgID":"5afad3a0de0dc60001ffdd07","config_data":{"bar":{"y":3},"foo":4}} type=log-msg
[Jun 13 14:45:21]  INFO jsvm-logmsg: Request object: {"Body":"","Headers":{"Accept":["*/*"],"Location":["/get"],"User-Agent":["curl/7.54.0"]},"Params":{"param1":["I-am-param-1"]},"URL":"/testvirtualendpoint2/headers"} type=log-msg
[Jun 13 14:45:21]  INFO jsvm-logmsg: Request Body: "" type=log-msg
[Jun 13 14:45:21]  INFO jsvm-logmsg: Request Headers:{"Accept":["*/*"],"Location":["/get"],"User-Agent":["curl/7.54.0"]} type=log-msg
[Jun 13 14:45:21]  INFO jsvm-logmsg: param-1:I-am-param-1 type=log-msg
[Jun 13 14:45:21]  INFO jsvm-logmsg: Request header type:[object Object] type=log-msg
[Jun 13 14:45:21]  INFO jsvm-logmsg: Request header: ["/get"] type=log-msg
[Jun 13 14:45:21]  INFO jsvm-logmsg: Request location type: object type=log-msg
[Jun 13 14:45:21]  INFO jsvm-logmsg: Request location type: string type=log-msg
[Jun 13 14:45:21]  INFO jsvm-logmsg: Request location: /get type=log-msg
--- before get to upstream ---
--- After get to upstream ---
[Jun 13 14:45:22]  INFO jsvm-logmsg: response type: string type=log-msg
[Jun 13 14:45:22]  INFO jsvm-logmsg: response: {"Code":200,"Body":"{\"headers\":{\"Accept-Encoding\":\"gzip\",\"Connection\":\"close\",\"Host\":\"httpbin.org\",\"Location\":\"/get\",\"User-Agent\":\"Go-http-client/1.1\"}}\n","Headers":{"Access-Control-Allow-Credentials":["true"],"Access-Control-Allow-Origin":["*"],"Content-Length":["133"],"Content-Type":["application/json"],"Date":["Wed, 13 Jun 2018 13:45:21 GMT"],"Server":["gunicorn/19.8.1"],"Via":["1.1 vegur"]},"code":200,"body":"{\"headers\":{\"Accept-Encoding\":\"gzip\",\"Connection\":\"close\",\"Host\":\"httpbin.org\",\"Location\":\"/get\",\"User-Agent\":\"Go-http-client/1.1\"}}\n","headers":{"Access-Control-Allow-Credentials":["true"],"Access-Control-Allow-Origin":["*"],"Content-Length":["133"],"Content-Type":["application/json"],"Date":["Wed, 13 Jun 2018 13:45:21 GMT"],"Server":["gunicorn/19.8.1"],"Via":["1.1 vegur"]}} type=log-msg
Virtual Test ended
[Jun 13 14:45:22] DEBUG JSVM Virtual Endpoint execution took: (ns) 191031553
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment