How to get a variable argument in the url in the virtual endpoint js function

Hi,

I’m facing a issue with batch.

Now the following code is working fine …

But I want to use the contact part dynamically (it will change in different request) “relative_url”: “http://10.32.0.8:8073/customer/contact/**436641234567**”

Currently I’m hard-coding it, so is there a way to get that dynamic variable arg part from any where.

Here i set up a virtual path and my function is “myVirtualTest” and my path is “customer/contact/{id}”

function generateUUID() {
** var d = new Date().getTime();**
** var uuid = ‘xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx’.replace(/[xy]/g, function(c) {**
** var r = (d + Math.random()16)%16 | 0;*
** d = Math.floor(d/16);**
** return (c==‘x’ ? r : (r&0x3|0x8)).toString(16);**
** });**
** return uuid;**
}

function myVirtualTest(request, session, config) {


** var correlationId = generateUUID();**

** // Set up a response object. Assume all will be successful.**
** var response = {**
** Body: “”**
** Headers: { “Content-Type”: “application/json”, “Access-Control-Allow-Origin”: “*”, “X-Correlation-Id”: correlationId},**
** Code: 200**
** };**


** var batch = {**
** “requests”: [**
** {**
** “method”: “GET”,**
** “headers”: {“Accept”: “application/json”, “X-Correlation-Id”: correlationId},**
** “relative_url”: “http://10.32.0.8:8073/customer/contact/436641234567”**
** }**
** ]**
** };**

** var resps = TykBatchRequest(JSON.stringify(batch));**
** var asJS = JSON.parse(resps)[0]; // there’s only one response.**
** response.Body = asJS.body;**
** return TykJsResponse(response, session.meta_data);**
}

You know that Tyk has built in support for injecting a correlation ID into a header right?

You just:

  1. Enable context variables
  2. Open the global option in the endpoint designer
  3. Click on the header injector
  4. Add header: X-Correlation-Id: $tyk_context.request_id

This will now add a unique ID to each request that goes through the gateway, not JS UUID generation needed.

To get that part of the URL, you could do something like (pseudocode, untested!):

var url_parts = request.URL.split("/")
var last_part = url_parts[url_parts.length - 1]

That should provide the last variable for you

Hi Martin,

Thanks a lot.

Sorry for late response.

No I was not aware of the first option, but i’m already using the second option given by you.

I found the second option while I was checking the request json format in the documentation.

But yes the first one is the best way to do it. I’ll change it.

Thanks,
Abhishek