user935219
user935219

Reputation: 93

Caching an HTTP request made from a Rails API (google-id-token)?

ok, first time making an API!

My assumption is that if data needs to be stored on the back end such that it persists across multiple API calls, it needs to be 1) in cache or 2) in a Database. is that right?

I was looking at the code for the gem "google-id-token". it seems to do just what i need for my google login application. My front end app will send the google tokens to the API with requests.

the gem appears to cache the public (PEM) certificates from Google (for an hour by default) and then uses them to validate the Google JWT you provide.

but when i look at the code (https://github.com/google/google-id-token/blob/master/lib/google-id-token.rb) it just seems to fetch the google certificates and put them into an instance variable.

am i right in thinking that the next time someone calls the API, it will have no memory of that stored data and just fetch it again?

i guess its a 2 part question:

  1. if i put something in an @instance_variable in my API, will that data exist when the next API call comes in?
  2. if not, is there any way that "google-id-token" is caching its data correctly? maybe HTTP requests are somehow cached on the backend and therefore the network request doesnt actually happen over and over? can i test this?

my impulse is to write "google-id-token" functionality in a way that caches the google certs using MemCachier. but since i dont know what I'm doing i thought i would ask.? Maybe the gem works fine as is, i dont know how to test it.

Upvotes: 1

Views: 595

Answers (1)

sam
sam

Reputation: 1161

Not sure about google-id-token, but Rails instance variables are not available beyond single requests and views (and definitely not from one user's session to another).

You can low-level cache anything you want with Rails.cache.fetch this is put in a block, takes a key name, and an expiration. So it looks like this:

Rails.cache.fetch("google-id-token", expires_in: 24.hours) do
  @instance_variable = something
end

If the cache exists and it is not past its expiration date/time, Rails grabs it from the cache; otherwise, it would make your API request.

It's important to note that low-level caching doesn't work with mem_store (the default for development) and so you need to implement a solution with redis or memcached or something like that for development, too. Also, make sure the file tmp/cache.txt exists. You can run rails dev:cache or just touch it to create it.

More on Rails caching

Upvotes: 1

Related Questions