forked from CodebuffAI/codebuff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch-usage.ts
More file actions
76 lines (65 loc) · 2.04 KB
/
Copy pathfetch-usage.ts
File metadata and controls
76 lines (65 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { getAuthToken } from './auth'
import { getApiClient } from './codebuff-api'
import { logger } from './logger'
import { useChatStore } from '../state/chat-store'
import type { CodebuffApiClient } from './codebuff-api'
import type { Logger } from '@codebuff/common/types/contracts/logger'
export interface FetchAndUpdateUsageParams {
showBanner?: boolean
getAuthToken?: () => string | undefined
getChatStore?: () => {
sessionCreditsUsed: number
setInputMode: (mode: 'usage' | 'default') => void
}
logger?: Logger
apiClient?: CodebuffApiClient
}
/**
* Fetches current usage data from the API and updates the chat store.
* If `showBanner` is true, makes the usage banner visible after updating.
* Returns true if successful, false otherwise.
*/
export async function fetchAndUpdateUsage(
params: FetchAndUpdateUsageParams = {},
): Promise<boolean> {
const {
showBanner = false,
getAuthToken: getAuthTokenFn = getAuthToken,
getChatStore = () => useChatStore.getState(),
logger: loggerInstance = logger,
apiClient: providedApiClient,
} = params
const authToken = getAuthTokenFn()
const chatStore = getChatStore()
if (!authToken) {
loggerInstance.debug('Cannot fetch usage: not authenticated')
return false
}
const apiClient =
providedApiClient ?? getApiClient()
try {
const response = await apiClient.usage()
if (!response.ok) {
loggerInstance.error(
{ status: response.status, errorText: response.error },
'Usage request failed',
)
return false
}
// Note: This function is deprecated. Use useUsageQuery hook instead.
// We no longer update the store here since usage data is managed by TanStack Query.
if (showBanner) {
chatStore.setInputMode('usage')
}
return true
} catch (error) {
loggerInstance.error(
{
error: error instanceof Error ? error.message : String(error),
errorStack: error instanceof Error ? error.stack : undefined,
},
'Error fetching usage',
)
return false
}
}