Skip to content
This repository has been archived by the owner on Jul 14, 2022. It is now read-only.

Quick Start: Add Caching

jwest-apigee edited this page Sep 6, 2014 · 9 revisions

Adding caching to your API

Adding caching is very similar to adding a quota.

  • First, update your package.json file in your project to include the volos-cache-memory": module under
        "dependencies": {
             "express": "",
             "a127-magic": "",
             "volos-cache-memory": ""
        }

Note: You can also use a cache implementation that uses Redis or Apigee as its provider. More information here.

  • Run, npm install.

  • Execute a127 project edit to open up the Swagger editor.

  • In the Swagger configuration file, under x-volos-resources, add the following to enable an in-memory cache provider named 'cache' that you refer to later:

        cache:     
            provider: volos-cache-memory
            options:
                name: weather-cache
                ttl: 60000
  • Finally, use x-volos-apply to apply this policy to the paths you want to enforce quotas on, referencing the resource you defined in the previous step:
        paths:     
            /weather:
                x-swagger-router-controller: weather
                x-volos-authorizations: {}
                x-volos-apply:
                    quota: {}
                    cache: {}

Now, try running the app as in the quickstart and try using the curl command:

        $ a127 project start
        $ curl http://localhost:10010/weather\?city\=San%20Jose,CA

Using a Helper Function to Customize Caching

If you do not specify a helper function to evaluate the Cache Key the entire URI will be used. This is less effective if you have API keys or other query parameters that result in many distinct URIs that could be cached using the same key.

The example above shows how you can use a single query parameter, city in this case, as the Cache Key

paths:
    /weather_cached:
        x-swagger-router-controller: weather
        x-volos-apply:
          cache: 
            key:
              helper: volos
              function: cacheKey
        get:
          ...

Using this annotation instructs Volos.js to call the function cacheKey in the helper module volos which it will look for in api/helpers by default. Here is an example implementation that uses the city query parameter to evaluate the Cache key:

module.exports = {
  cacheKey: cacheKey,
};

function cacheKey(req) {
// This can check for a specific query parameter
  var key = req.swagger.params.city.value;
  console.log('Cache Key: '+key)
  return key;
}

This can be customized to do whatever logic you wish to use to evaluate the Cache key, but don't add too much complexity or your latency may go way up!

Next steps

You can also add quotas, OAuth, analytics, and deploy to Apigee.

Clone this wiki locally