|
|
import { useQuery } from '@tanstack/react-query'; |
|
|
import wpcom from 'calypso/lib/wp'; |
|
|
import getDefaultQueryParams from 'calypso/my-sites/stats/hooks/default-query-params'; |
|
|
import { getApiNamespace } from '../lib/get-api'; |
|
|
|
|
|
type Module = 'akismet' | 'protect' | 'vaultpress' | 'monitor' | 'stats' | 'verification-tools'; |
|
|
type ModuleData = number | string | boolean; |
|
|
interface ErrorResponse { |
|
|
code: string; |
|
|
message: string | undefined; |
|
|
} |
|
|
|
|
|
function queryModuleData( module: Module ): Promise< ModuleData > { |
|
|
|
|
|
return wpcom.req |
|
|
.get( { |
|
|
method: 'GET', |
|
|
|
|
|
apiNamespace: getApiNamespace(), |
|
|
path: `/module/${ module }/data`, |
|
|
} ) |
|
|
.catch( ( error: Error & ErrorResponse ) => { |
|
|
if ( error?.code === 'not_active' ) { |
|
|
|
|
|
throw new Error( error.code ); |
|
|
} |
|
|
throw error; |
|
|
} ) |
|
|
.then( ( response: ModuleData ) => { |
|
|
|
|
|
if ( response === 'false' || response === false ) { |
|
|
return 0; |
|
|
} |
|
|
|
|
|
if ( ! isNaN( parseInt( response as string ) ) ) { |
|
|
return parseInt( response as string ); |
|
|
} |
|
|
throw new Error( response as string ); |
|
|
} ); |
|
|
} |
|
|
|
|
|
export default function useModuleDataQuery( module: Module ) { |
|
|
return useQuery( { |
|
|
...getDefaultQueryParams(), |
|
|
queryKey: [ 'stats-widget', 'module-data', module ], |
|
|
queryFn: () => queryModuleData( module ), |
|
|
staleTime: 5 * 60 * 1000, |
|
|
|
|
|
retry: false, |
|
|
} ); |
|
|
} |
|
|
|