Skip to content

Commit

Permalink
Refetch defensive mode endpoint after it expires
Browse files Browse the repository at this point in the history
  • Loading branch information
fredrikekelund committed Oct 1, 2024
1 parent 4213383 commit 18d037e
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions client/data/hosting/use-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from '@tanstack/react-query';
import { useI18n } from '@wordpress/react-i18n';
import { useTranslate } from 'i18n-calypso';
import { useCallback } from 'react';
import { useCallback, useEffect } from 'react';
import wp from 'calypso/lib/wp';
import { useDispatch } from 'calypso/state';
import { successNotice, errorNotice, plainNotice } from 'calypso/state/notices/actions';
Expand Down Expand Up @@ -184,7 +184,7 @@ type EdgeCacheDefensiveModeQueryData = {
};

export function useEdgeCacheDefensiveModeQuery( siteId: number | null ) {
return useQuery< EdgeCacheDefensiveModeQueryData >( {
const query = useQuery< EdgeCacheDefensiveModeQueryData >( {
queryKey: getEdgeCacheDefensiveModeQueryKey( siteId ),
queryFn: () =>
wp.req.get( {
Expand All @@ -193,6 +193,27 @@ export function useEdgeCacheDefensiveModeQuery( siteId: number | null ) {
} ),
enabled: siteId !== null,
} );

const { data, refetch } = query;
const enabled = data?.enabled ?? false;
const enabledUntil = data?.enabled_until ?? 0;

// Refetch the defensive mode API endpoint ten seconds after it's set to disable
useEffect( () => {
if ( ! enabled ) {
return;
}

const msDiff = enabledUntil * 1000 - Date.now();
const delay = Math.max( 0, msDiff ) + 10000;
const timeoutId = setTimeout( () => refetch(), delay );

return () => {
clearTimeout( timeoutId );
};
}, [ enabled, enabledUntil, refetch ] );

return query;
}

type EdgeCacheDefensiveModeMutationVariables = { active: true; ttl: number } | { active: false };
Expand Down

0 comments on commit 18d037e

Please sign in to comment.