Repository navigation
refactor: extract shared useApiRequest composable for axios services #13402
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mattmillerai
wants to merge
18
commits into
main
Choose a base branch
from
matt/be-2254-extract-api-request-composable
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+844
−263
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
6b61a56
refactor: extract shared useApiRequest composable for axios services
mattmillerai 58f541b
test: cover comfyRegistryService and comfyManagerService request wrap…
mattmillerai 4e0298d
fix: make useApiRequest loading state concurrency-safe
mattmillerai 4647dce
Merge remote-tracking branch 'origin/main' into matt/be-2254-extract-…
mattmillerai b736b37
fix: address review findings on error mapping and queue-start propaga…
mattmillerai 5ee55c5
Merge remote-tracking branch 'origin/main' into matt/be-2254-extract-…
mattmillerai 15f87af
Merge remote-tracking branch 'origin/main' into matt/be-2254-extract-…
mattmillerai 6f7ddba
fix: report queue-start failure instead of throwing
mattmillerai f6b559b
fix: derive queue-start outcome per request instead of shared error s…
mattmillerai d7931f6
Merge origin/main into matt/be-2254-extract-api-request-composable
mattmillerai bd1955e
fix: narrow axios errors with isAxiosError<T> instead of casting
mattmillerai e6286fd
fix: keep a stale customer-events failure from overwriting a newer re…
mattmillerai a8d8746
Merge remote-tracking branch 'origin/main' into matt/be-2254-extract-…
mattmillerai 5cf569d
fix: treat axios cancellations as aborts in useApiRequest
mattmillerai f045413
Merge remote-tracking branch 'origin/main' into matt/be-2254-extract-…
mattmillerai d5b9722
Merge remote-tracking branch 'origin/main' into matt/be-2254-extract-…
mattmillerai e82889d
Merge remote-tracking branch 'origin/main' into matt/be-2254-extract-…
mattmillerai d238397
refactor: drop the unused isCurrent option from useApiRequest
mattmillerai File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| import type { AxiosResponse } from 'axios' | ||
| import axios, { AxiosHeaders, CanceledError } from 'axios' | ||
| import { describe, expect, it, vi } from 'vitest' | ||
|
|
||
| import { useApiRequest } from '@/composables/useApiRequest' | ||
|
|
||
| const client = axios.create() | ||
|
|
||
| function response<T>(data: T): AxiosResponse<T> { | ||
| return { | ||
| data, | ||
| status: 200, | ||
| statusText: 'OK', | ||
| headers: {}, | ||
| config: { headers: new AxiosHeaders() } | ||
| } | ||
| } | ||
|
|
||
| describe('useApiRequest', () => { | ||
| it('returns response data and toggles loading state', async () => { | ||
| const { isLoading, error, executeRequest } = useApiRequest({ | ||
| client, | ||
| mapError: vi.fn() | ||
| }) | ||
| expect(isLoading.value).toBe(false) | ||
|
|
||
| const pending = executeRequest(async () => response('ok'), { | ||
| errorContext: 'ctx' | ||
| }) | ||
| expect(isLoading.value).toBe(true) | ||
|
|
||
| await expect(pending).resolves.toBe('ok') | ||
| expect(isLoading.value).toBe(false) | ||
| expect(error.value).toBeNull() | ||
| }) | ||
|
|
||
| it('stays loading until every concurrent request settles', async () => { | ||
| const { isLoading, executeRequest } = useApiRequest({ | ||
| client, | ||
| mapError: vi.fn() | ||
| }) | ||
|
|
||
| let resolveFirst!: (value: AxiosResponse<string>) => void | ||
| const first = executeRequest( | ||
| () => new Promise<AxiosResponse<string>>((res) => (resolveFirst = res)), | ||
| { errorContext: 'ctx' } | ||
| ) | ||
| const second = executeRequest(async () => response('second'), { | ||
| errorContext: 'ctx' | ||
| }) | ||
|
|
||
| await second | ||
| expect(isLoading.value).toBe(true) | ||
|
|
||
| resolveFirst(response('first')) | ||
| await first | ||
| expect(isLoading.value).toBe(false) | ||
| }) | ||
|
|
||
| it('passes the injected client to the api call', async () => { | ||
| const apiCall = vi.fn(async () => response(1)) | ||
| const { executeRequest } = useApiRequest({ client, mapError: vi.fn() }) | ||
|
|
||
| await executeRequest(apiCall, { errorContext: 'ctx' }) | ||
|
|
||
| expect(apiCall).toHaveBeenCalledWith(client) | ||
| }) | ||
|
|
||
| it('maps errors through the injected mapper and stores the message', async () => { | ||
| const mapError = vi.fn(() => 'mapped message') | ||
| const routeSpecificErrors = { 404: 'nope' } | ||
| const boom = new Error('boom') | ||
| const { error, executeRequest } = useApiRequest({ client, mapError }) | ||
|
|
||
| const result = await executeRequest( | ||
| () => { | ||
| throw boom | ||
| }, | ||
| { errorContext: 'ctx', routeSpecificErrors } | ||
| ) | ||
|
|
||
| expect(result).toBeNull() | ||
| expect(mapError).toHaveBeenCalledWith(boom, 'ctx', routeSpecificErrors) | ||
| expect(error.value).toBe('mapped message') | ||
| }) | ||
|
|
||
| it.for([ | ||
| { | ||
| kind: 'DOM AbortError', | ||
| cancellation: new DOMException('aborted', 'AbortError') | ||
| }, | ||
| { kind: 'axios CanceledError', cancellation: new CanceledError() } | ||
| ])('swallows a $kind without mapping an error', async ({ cancellation }) => { | ||
| const mapError = vi.fn(() => 'should not run') | ||
| const { error, executeRequest } = useApiRequest({ client, mapError }) | ||
|
|
||
| const result = await executeRequest( | ||
| () => { | ||
| throw cancellation | ||
| }, | ||
| { errorContext: 'ctx' } | ||
| ) | ||
|
|
||
| expect(result).toBeNull() | ||
| expect(mapError).not.toHaveBeenCalled() | ||
| expect(error.value).toBeNull() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| import type { AxiosInstance, AxiosResponse } from 'axios' | ||
| import axios from 'axios' | ||
| import { computed, ref } from 'vue' | ||
|
|
||
| import { isAbortError } from '@/utils/typeGuardUtil' | ||
|
|
||
| /** | ||
| * Maps a caught request error to a user-facing message string. | ||
| * Each service injects its own mapper so it keeps control of the exact | ||
| * status-to-message copy it presents. | ||
| */ | ||
| export type ApiErrorMapper = ( | ||
| err: unknown, | ||
| errorContext: string, | ||
| routeSpecificErrors?: Record<number, string> | ||
| ) => string | ||
|
|
||
| export interface ExecuteRequestOptions { | ||
| errorContext: string | ||
| routeSpecificErrors?: Record<number, string> | ||
| } | ||
|
|
||
| /** | ||
| * Shared axios request wrapper: owns the `isLoading`/`error` state and the | ||
| * try/catch/finally plumbing, while the caller injects the axios instance and | ||
| * an error mapper. Cancellations are swallowed (no error set, `null` returned). | ||
| */ | ||
| export function useApiRequest({ | ||
| client, | ||
| mapError | ||
| }: { | ||
| client: AxiosInstance | ||
| mapError: ApiErrorMapper | ||
| }) { | ||
| const pendingCount = ref(0) | ||
| const isLoading = computed(() => pendingCount.value > 0) | ||
| const error = ref<string | null>(null) | ||
|
|
||
| async function executeRequest<T>( | ||
| apiCall: (client: AxiosInstance) => Promise<AxiosResponse<T>>, | ||
| options: ExecuteRequestOptions | ||
| ): Promise<T | null> { | ||
| const { errorContext, routeSpecificErrors } = options | ||
|
|
||
| pendingCount.value++ | ||
| error.value = null | ||
|
|
||
| try { | ||
| const response = await apiCall(client) | ||
| return response.data | ||
| } catch (err) { | ||
| if (isAbortError(err) || axios.isCancel(err)) return null | ||
|
|
||
| error.value = mapError(err, errorContext, routeSpecificErrors) | ||
| return null | ||
| } finally { | ||
| pendingCount.value-- | ||
| } | ||
| } | ||
|
|
||
| return { isLoading, error, executeRequest } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
38 changes: 38 additions & 0 deletions
38
src/platform/customNodes/manager/services/comfyManagerService.apiBase.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import type { InternalAxiosRequestConfig } from 'axios' | ||
| import axios from 'axios' | ||
| import { describe, expect, it, vi } from 'vitest' | ||
| import { computed } from 'vue' | ||
|
|
||
| import { api } from '@/scripts/api' | ||
| import { useManagerState } from '@/platform/customNodes/manager/composables/useManagerState' | ||
|
|
||
| vi.mock(import('axios'), { spy: true }) | ||
| vi.mock(import('@/scripts/api')) | ||
| vi.mock(import('@/platform/customNodes/manager/composables/useManagerState')) | ||
|
|
||
| const requestedUrl = vi.fn<(url: string) => void>() | ||
|
|
||
| async function captureRequestUrl(config: InternalAxiosRequestConfig) { | ||
| requestedUrl(axios.getUri(config)) | ||
| return { data: {}, status: 200, statusText: 'OK', headers: {}, config } | ||
| } | ||
|
|
||
| vi.mocked(axios.create).mockImplementationOnce((config) => | ||
| axios.create({ ...config, adapter: captureRequestUrl }) | ||
| ) | ||
|
|
||
| const { useComfyManagerService } = | ||
| await import('@/platform/customNodes/manager/services/comfyManagerService') | ||
|
|
||
| describe('useComfyManagerService', () => { | ||
| it('sends the request to the API base configured after import', async () => { | ||
| api.api_base = '/changed-base' | ||
| vi.mocked(useManagerState()).isNewManagerUI = computed(() => true) | ||
|
|
||
| await useComfyManagerService().listInstalledPacks() | ||
|
|
||
| expect(requestedUrl).toHaveBeenCalledWith( | ||
| '/changed-base/api/v2/customnode/installed' | ||
| ) | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.