ETag / Cache-Control headers on Strapi REST API

Hello,

I dug a little deeper into this subject and managed to achieve my goal in just a few lines of code, by reusing a combination of Koa middlewares: koa-cache-control, koa-conditional-get and koa-etag:

It can certainly be improved, but here is my code that may help others:

import { ParameterizedContext } from "koa";
import cacheControl from "koa-cache-control";
import koaConditionalGet from "koa-conditional-get";
import koaEtag from "koa-etag";

const cacheControlMiddleware = cacheControl({
  // TODO Write here the default cache control settings you want for your API
});

const conditionalMiddleware = koaConditionalGet();

const etagMiddleware = koaEtag();

export default () =>
  async (context: ParameterizedContext, next: () => Promise<any>) => {
    await next();

    // Exclude non cacheable methods
    if (!["HEAD", "GET"].includes(context.request.method)) {
      return;
    }

    // Exclude non successful responses
    if (context.status < 200 || context.status >= 300) {
      return;
    }

    await etagMiddleware(context, () => Promise.resolve());
    await conditionalMiddleware(context, () => Promise.resolve());
    await cacheControlMiddleware(context, () => Promise.resolve());
  };