Retrieve data from the cache

Get Cache Value

Catalyst cache is divided into partitions or cache units called segments. Each segment stores cache items in the form of key-value pairs. Both keys and values are of the String type.

You can retrieve the value of a cache item from a segment in the cache using the getValue() method. You must pass the key name as the argument. The promise returned here will be resolved to a String, which is the actual value of the key.

The segment reference used in the code snippet below is the segment instance created earlier.

Copied//Get cache value by passing the key name
    let cache = app.cache();
    let segment = cache.segment();
    let cachePromise = segment.getValue('Age');
    cachePromise.then((entity) => {
            console.log(entity);
        });

Get Cache Object

You can retrieve the details of the cache where the key-value pair is of the object type. The key object is retrieved using the get() method where the key name is passed as an argument. The segment reference used in the code snippet below is a segment instance. The promise returned here will be resolved to an object which is a JSON.

Copied//Get Cache object by passing the key name as argument
    let cache = app.cache();
    let segment = cache.segment();
    let cachePromise = segment.get('Age');
    cachePromise.then((entity) => {
            console.log(entity);
        });

A sample response that you will receive for each version is shown below:

Copied{
  cache_name: "Name",
  cache_value: "Amelia Burrows",
  project_details: { project_name: "AlienCity", id: 2136000000007733 },
  segment_details: { segment_name: "DataStore", id: 2136000000008572 },
  expires_in: "Aug 18, 2021 06:39 PM",
  expiry_in_hours: 47,
  ttl_in_milliseconds: 172609000
}
Copied{
  cache_name: "Name",
  cache_value: "Amelia Burrows",
  project_details: { project_name: "AlienCity", id: "2136000000007733" },
  segment_details: { segment_name: "DataStore", id: "2136000000008572" },
  expires_in: "Aug 18, 2021 06:39 PM",
  expiry_in_hours: "47",
  ttl_in_milliseconds: "172727000"
}