Javascript Request object without Domain

Hi all,

I have a usecase where I get the URL as a string but the Tyk HTTP request object requires me to specify Domain and the Resource. Are there any suggestions for any workaround to this?

This is the object example in the docs

newRequest = {
  "Method": "POST",
  "Body": JSON.stringify(event),
  "Headers": {},
  "Domain": "http://foo.com",
  "Resource": "/event/quotas",
  "FormData": {"field": "value"}
};

I want something like

newRequest = {
  "Method": "POST",
  "Body": JSON.stringify(event),
  "Headers": {},
  "Domain": "http://foo.com/event/quotas",
  "Resource": "",
  "FormData": {"field": "value"}
};

Unfortunately, I still get proxy error. Oddly, I see a 404 which makes no sense to me. Yes the URL is reachable otherwise and even if I split the Domain and Resource parts it works.

Are you looking to split the domain and resource so you can reconstruct the URL string in a format suitable to send a http request using Tyk’s JSVM?

function parse_url(url) {
  const match = url.match(/^(http|https|ftp)?(?:[\:\/]*)([a-z0-9\.-]*)(?:\:([0-9]+))?(\/[^?#]*)?(?:\?([^#]*))?(?:#(.*))?$/i);
  const ret = new Object();

  ret.protocol = '';
  ret.host = match[2];
  ret.port = '';
  ret.path = '';
  ret.query = '';
  ret.fragment = '';

  if (match[1]) {
    ret.protocol = match[1];
  }

  if (match[3]) {
    ret.port = match[3];
  }

  if (match[4]) {
    ret.path = match[4];
  }

  if (match[5]) {
    ret.query = match[5];
  }

  if (match[6]) {
    ret.fragment = match[6];
  }

  return ret;
}

function myFunc(request, session, config) {
  const url_parts = parse_url('http://google.com:8080/foo/bar/baz#frag?foo=bar');

  const responseObject = {
    Body: JSON.stringify({
      parts: url_parts.protocol,
      host: url_parts.host,
      port: url_parts.port,
      path: url_parts.path,
      query: url_parts.query,
      fragment: url_parts.fragment,
    }),
    Code: 200,
  };
  return TykJsResponse(responseObject, session.meta_data);
}

output when calling the endpoint:

HTTP/1.1 200 OK
Connection: close
Date: Thu, 29 Aug 2019 22:02:07 GMT
Server: tyk
X-Ratelimit-Limit: 0
X-Ratelimit-Remaining: 0
X-Ratelimit-Reset: 0

{"fragment":"frag?foo=bar","host":"google.com","parts":"http","path":"/foo/bar/baz","port":"8080","query":""} 
1 Like