swrv icon indicating copy to clipboard operation
swrv copied to clipboard

Disable swrv for certain endpoints

Open kgish opened this issue 2 years ago • 5 comments

I would like to be able to disable swrv for certain endpoints, is that possible?

For example, all calls to /api/comments should simple passthru and always make remote api calls.

Or is there an easier way to do this with useSWRV()?

kgish avatar Aug 21 '23 09:08 kgish

You would need to provide an example of how you’re using swrv in your project.

swrv doesn’t automatically “bind” to every request in your app, etc.

adamdehaven avatar Aug 21 '23 12:08 adamdehaven

This is a Vue3 application, and in the base API class SWRV is being hooked into all calls like this:

export function useApi<T extends resource | resource[]>(
  key: KeyFunction | string,
  resourcesToInclude: IncludeList = [],
  config: SWRV.IConfig = {}
): UseApiResponse<T> {

  const _config = {
    ...defaultConfig,
    ...config,
  };

  const {
    data: apiData,
    error,
    isValidating,
    mutate,
  } = useSWRV<AxiosResponse<JSONApiResponse<T>>>(
    key,
    (key) => {
      const url = addIncludesToPath(key, resourcesToInclude);
      return (api
          .get(url)
          .catch(error => Promise.reject([ errorAsApiError(error) ]))
      );
    },
    _config
  );

  const errors = computed(() => apiData.value?.data.errors || error.value);
  const included = computed(() => apiData.value?.data?.included;
  const meta = computed(() => apiData.value?.data?.meta);
  const data = computed(() => apiData.value?.data?.data;

  // These are intended for collections
  const links = computed(() => apiData.value?.data?.links);
  const pagination = computed(() => meta.value?.pagination);

  return {
    data,
    errors,
    meta,
    pagination,
    links,
    included,
    isValidating,
    mutate,
  };

If keys is /api/comments/... I would like to skip looking in the cache altogether.

kgish avatar Aug 21 '23 12:08 kgish

The easiest way would be to just provide a dynamic key (in your wrapper function) for any request utilizing the /api/comments/** path, for example new Date().getTime()

Since the cache key will be different on every request, it won't read from the cache.

adamdehaven avatar Aug 21 '23 13:08 adamdehaven

But doesn't that mean that the cache will then be polluted with all kinds of irrelevant hash key values, since I am assuming that when the call returns it will be adding the key- value (url - response) to the cache?

kgish avatar Aug 21 '23 13:08 kgish

You could also override the cache provider for URLs that match a certain syntax, or set the ttl to 1 so that the requests essentially are never valid in the cache.

adamdehaven avatar Aug 21 '23 14:08 adamdehaven