cancel
Showing results for 
Search instead for 
Did you mean: 

Cache external/remote request body

SOLVED
Highlighted
New Contributor

Cache external/remote request body

Hi Folks,

I need to access an external file which responds a JSON. The JSON file will not be updated so frequently and hence we need to change the response.

Please suggest a way to implement caching of remote request in TS and also updating the cache when the file has changed.

Thanks in advance.

Regards,

Munim

4 REPLIES
Contributor

Re: Cache external/remote request body

Hi,

you can request the external file via


$body = http.request.get( "https://www.example.com/",   "Cookie: foo=bar" );


then store the result (json) in memory (after your modification) via


data.set("mycache",$body);


and deliver the result, depending on cache setting (how do you know that the external content had changed without requesting it every time?)

you can fetch your stored value via


$body = data.get("mycache");


deliver the result with


http.sendResponse( "200 OK",


                 "application/json",


                 $body,


                 "" );


-Jochen

New Contributor

Re: Cache external/remote request body

Hi Jochen,

Thank you for your response. the solution will invoke example.com on every request which I want to eliminate.

I will have a static JSON file in my situation. Is there anyway to identify if the file has changed/modified by timestamp and not reading the whole JSON file rather than reading it from the cache?

My ultimate goal is not to read the file on every request rather than reading the file once (if changed) and update the cache.

Please suggest.

Regards,

Munim

Contributor

Re: Cache external/remote request body

Hi Munim,

depending on the information you get with your first request (http-headers, expires setting, cache-control etc.) you can make the decision if you have to request it again...

-Jochen

Moderator

Re: Cache external/remote request body

Munim,

the http.request.get() supports passing of headers to the server you are requesting from.  You could use a "Conditional GET" (See RFC for more details: HTTP/1.1: Method Definitions) to the external server that is serving the JSON response by specifying an appropriate header such as "If-Modified-Since".  In your TS logic, when you retrieve the file, you can store the relevant date/time stamp with a data.set() call, and then use the date value that you last stored when constructing the next http.request.get() call. The HTTP Response code from the external server is returned as $1 from http.request.get(), so if you get an HTTP response of 304 (ie: content not modified) then you know you can serve the cached document.

does this help?