e-Spirit / javascript-content-api-library

Apache License 2.0
7 stars 11 forks source link

Sub Requests triggered by DatasetReference are not cacheable correctly #212

Open cbou opened 1 month ago

cbou commented 1 month ago

In headless situation, caching is very important, especially for requests triggered to the backend.

In my project, I use fetchByFilter to get some objects. To prevent making too much request to the backend I rely on the cache mechanism of NextJS: https://nextjs.org/docs/app/building-your-application/data-fetching I pass a fetchOptions object with the information about the caching to fetchByFilter. e.g.:

    fetchOptions: {
      next: {
        tags: ["my-tag"],
        revalidate: 3600,
      },
    },

NextJS will cache the response of the fetch for one hour. The next calls will be served from the cache instead of from the backend. It works well.

If the returned objects contains some DatasetReference. Sub requests will be triggered internally by the fsxa-api library. However the fetchOptions param is lost and not passed by the original fetchByFilter call.

This makes caching of sub request impossible.

I was able to check that by adding some extra logging.

FSXARemoteApi.js

    FSXARemoteApi.prototype.fetchByFilter = function (_a, mapper) {
        console.log('Fetch by filter');
        console.log(_a.fetchOptions);

The produced log:

$ npx ts-node index-countries.ts
Fetch by filter
{ next: { tags: [ 'my-tag' ], revalidate: 3600 } }
Fetch by filter
undefined
Fetch by filter
undefined
Fetch by filter
undefined
Fetch by filter
undefined
Fetch by filter

Is there a way to make sure the fetchOptions is pass to sub fetchByFilter calls?

jodeleit-es commented 1 month ago

There is currently no way to get fetchOptions propagated to subsequent requests. And I doubt that it would be a good idea to have these propagated by default. You can e.g. opt-out of automatic reference resolving (by setting the depth to zero) and do then the resolving yourself (including your desired options).

But we may accept a patch as long as it is non-breaking (ie with an opt-in flag).