Populate cache expiry time in milliseconds

Hi,

We have a use case where we are getting the access token expiry time from backend API in milliseconds from 1970, Jan 1 epoch time. How can we specify this expiry in Populate cache policy to store the token in cache.

Solved Solved
0 5 639
1 ACCEPTED SOLUTION

Use a JavaScript and divide your value by 1000.

<Javascript name='JS-1' >
  <Source>
    var value_from_backend = Number(context.getVariable('value_from_backend'));
    var inSeconds = Math.floor(value_from_backend/1000);
    context.setVariable('duration_variable', inSeconds.toFixed(0));
  </Source>
</Javascript>

Then specify the PopulateCache element TimeoutInSeconds, with a ref.

  <ExpirySettings>
    <TimeoutInSec ref='duration_variable'/>
  </ExpirySettings>

the duration_variable is the one you set in your preceding JavaScript.

View solution in original post

5 REPLIES 5

Use a JavaScript and divide your value by 1000.

<Javascript name='JS-1' >
  <Source>
    var value_from_backend = Number(context.getVariable('value_from_backend'));
    var inSeconds = Math.floor(value_from_backend/1000);
    context.setVariable('duration_variable', inSeconds.toFixed(0));
  </Source>
</Javascript>

Then specify the PopulateCache element TimeoutInSeconds, with a ref.

  <ExpirySettings>
    <TimeoutInSec ref='duration_variable'/>
  </ExpirySettings>

the duration_variable is the one you set in your preceding JavaScript.

I think they need to additionally have

...

var currentTime = new Date().getTime()

var timeout = Math.floor((value_from_backend-currentTime)/1000);

if (timeout > 0) {

context.setVariable('duration_variable', inSeconds.toFixed(0));

}

Yes, possibly! If the "expiry" from the backend is expressed in absolute time, then... yes, this subtraction is necessary.

If the expiry from the backend is expressed in relative time (how many milliseconds from "now"), then... they don't need to subtract "current time".

Thank you for pointing this out!

Is it possible to do these Mathematical operations in Assign message policy like below ?

    <AssignVariable>
        <Name>systemtime</Name>
        <Ref>system.timestamp</Ref>
    </AssignVariable>
    <AssignVariable>
        <Name>expires_in</Name>
        <Template>{expires_at} - {substring(systemtime,0,10)}</Template>
    </AssignVariable>

Note when using message templates

https://docs.apigee.com/api-platform/reference/message-template-intro

any text not in curly braces is output as literal text

Also, if it was to try and do the subtraction, it's not going to work if you have a string..