// src/hooks/useRecordUsage.ts
import { useMutation, UseMutationOptions } from "@tanstack/react-query";
export type UsageEventData = {
subscriptionId: string,
quantity: number,
metric: string,
eventId?: string,
metadata?: Record<string, any>,
};
export type RecordUsageResponse = {
success: boolean,
usageEventId: string,
duplicate: boolean,
};
const useApiKey = () => {
// !! REPLACE THIS PLACEHOLDER !!
const apiKey = 'YOUR_CREDIBILL_API_KEY';
return apiKey;
};
const CREDIBILL_URL = 'https://giant-goldfish-922.convex.site';
const ENDPOINT = '/api/v1/usage';
type UseRecordUsageOptions = Omit<UseMutationOptions<
RecordUsageResponse,
Error,
UsageEventData
> , 'mutationFn'>;
/\*\*
- Custom React Query hook for recording usage events
- @param options - Optional configuration options for useMutation
- @returns The mutation object provided by TanStack Query
\*/
export const useRecordUsage = (
options?: UseRecordUsageOptions
) => {
const apiKey = useApiKey();
return useMutation<RecordUsageResponse, Error, UsageEventData>({
mutationFn: async (data: UsageEventData) => {
if (!apiKey) {
throw new Error("API Key is required for authentication.");
}
const response = await fetch(`${CREDIBILL_URL}${ENDPOINT}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
body: JSON.stringify(data),
});
if (!response.ok) {
const errorBody = await response.json();
throw new Error(errorBody.error || `HTTP error! Status: ${response.status}`);
}
return response.json();
},
...options,
});
};