1

I have an endpoint in API Gateway for path: /v1/services that returns all services in DynamoDB.

It is possible also to add query parameter like: /v1/services?search={something} and in this case services will be filtered depending on search string.

I added caches using stageOptions/methodOption like this:

methodOptions: {
            '/v1/services/GET': {
              cacheDataEncrypted: true,
              cachingEnabled: true,
              cacheTtl: Duration.minutes(3)
            }
          }

But in this case both /v1/services and /v1/services?search={something} requests will be cached for 3 minutes.

Is there a way to do add caches only for /v1/services so only if no query parameters are present in request using AWS cdk?

Davide Bracaglia
  • 159
  • 1
  • 1
  • 12

2 Answers2

0

So depending upon the Integration type you are using you can specify the individual cache key parameters that you want to be included when building what's cached

I haven't personally done it, but I believe the syntax is close to something like this for a Lambda Integration

 new apigw.LambdaIntegration('<VERB>', {
    proxy: true,
    allowTestInvoke: true,
    cacheKeyParameters: ["method.request.path.id"],
    cacheNamespace: "someId",
    requestParameters: {
      "integration.request.path.id": "method.request.path.id",
    },
  }),
  {
    requestParameters: {
      "method.request.path.id": true,
    },
  }
);

API Gateway Docs

CDK LambdaIntegrationOptions

Benjamen
  • 65
  • 1
  • 5
0

Enable caching in api gateway, enable caching in API gateway

 const apigw = new LambdaRestApi(this, "productApi", {
  proxy: false,
  restApiName: "productService",
  handler: productMicroService,
  // deploy should be true for deployOptions
  deploy: true,
  deployOptions: {
    // this enables caching on api gateway, with a ttl of five minutes 
   (unless overridden per method)
    cachingEnabled: true, // responses should be cached and returned for 
    requests
    cacheClusterEnabled: true,
    cacheDataEncrypted: true,
    stageName: "prod",
    cacheTtl: Duration.minutes(5),
    // ensure that our caching is done on the id path parameter
  },
});

const product = apigw.root.addResource("product");
product.addMethod("GET", queryintegration, {
  requestParameters: {
    "method.request.querystring.category": true,
  },
});

const queryintegration = new LambdaIntegration(productMicroService, {
  cacheKeyParameters: ["method.request.querystring.category"],
  requestParameters: {
    "integration.request.querystring.category":
      "method.request.querystring.category",
  },
});

You can also use this with path parameters caching using "method.request.path.id"

Sehrish Waheed
  • 1,230
  • 14
  • 17