Kong / swrv

Stale-while-revalidate data fetching for Vue

Home Page:https://docs-swrv.netlify.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Disable swrv for certain endpoints

kgish opened this issue · 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()?

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.

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.

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.

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?

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.