DEV Community

Manish Kumar
Manish Kumar

Posted on Edited on

Decoupling HTTP Clients in Vue 3: Extracting API Modules and Converting PendingSubmissionsPill to TypeScript

A common anti-pattern in frontend development is calling HTTP client libraries (like axios or native fetch) directly inside Vue UI components. When components perform raw network calls, testing becomes cumbersome, endpoints cannot be reused, and frontend code is coupled to specific networking libraries.

In my recent contribution to GitLab's Contributors Platform (MR !3201, closing Issue #880), I migrated the PendingSubmissionsPill navigation component to TypeScript and extracted its API interactions into a dedicated, typed client module.

Here is an architectural walkthrough of decoupling HTTP interactions from components and testing them cleanly in Vitest.


1. The Anti-Pattern: Direct Axios Calls Inside Components

In the navigation bar, PendingSubmissionsPill.vue displays a badge showing how many community submissions (blog posts, talks, events) are pending reviewer approval.

Previously, the component called axios directly:

<!-- Before (JavaScript) -->
<script setup>
import axios from 'axios';
import { ref } from 'vue';

const count = ref(0);

const fetchCount = async () => {
  try {
    const { data } = await axios.get('/api/v1/submissions/count');
    count.value = data.count;
  } catch {
    error.value = true;
  }
};
</script>
Enter fullscreen mode Exit fullscreen mode

Why this is problematic:

  1. Coupling: The UI component is tightly coupled to Axios. Migrating to another client or adding global interceptors requires touching multiple Vue SFCs.
  2. Brittle Mocking: Unit tests had to mock global axios.get calls using URLs as magic strings ('/api/v1/submissions/count'), making tests fragile when endpoints evolve.
  3. No Contract Validation: Response data was untyped, leaving data.count unchecked by the compiler.

2. Step 1: Extracting a Typed API Service Layer

We created a dedicated client module in ~/api/submissions.ts, leveraging generated OpenAPI response types:

// app/javascript/api/submissions.ts
import axios from 'axios';
import type { GetApiV1SubmissionsCountResponse } from '~/api/generated';

export async function fetchSubmissionsCount(): Promise<GetApiV1SubmissionsCountResponse> {
  const { data } = await axios.get<GetApiV1SubmissionsCountResponse>(
    '/api/v1/submissions/count'
  );

  return data;
}
Enter fullscreen mode Exit fullscreen mode

We accompanied this with an isolated unit test in api/submissions.spec.ts:

import axios from 'axios';
import { PLACEHOLDER_AXIOS_RESPONSE } from '~/spec/mockFactories';
import { fetchSubmissionsCount } from './submissions';

describe('fetchSubmissionsCount', () => {
  it('gets and returns data from the submissions count endpoint', async () => {
    const get = vi.spyOn(axios, 'get').mockResolvedValue(PLACEHOLDER_AXIOS_RESPONSE);

    const result = await fetchSubmissionsCount();

    expect(get).toHaveBeenCalledWith('/api/v1/submissions/count');
    expect(result).toBe(PLACEHOLDER_AXIOS_RESPONSE.data);
  });
});
Enter fullscreen mode Exit fullscreen mode

3. Step 2: Refactoring the Vue Component

With the network layer isolated, PendingSubmissionsPill.vue became a pure presentation component focused exclusively on UI state and browser lifecycle events:

<!-- After (TypeScript) -->
<script setup lang="ts">
import { BBadge, BNavItem } from 'bootstrap-vue-next';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { fetchSubmissionsCount } from '~/api/submissions';
import { useSubmissionsRefresh } from '~/common/useSubmissionsRefresh';
import { useVueData } from '~/common/useVueData';

const { pendingSubmissionsCount } = useVueData();
const count = ref(pendingSubmissionsCount);
const error = ref(false);

const fetchCount = async () => {
  try {
    const data = await fetchSubmissionsCount();
    count.value = data.count;
    error.value = false;
  } catch {
    error.value = true;
  }
};

// Re-fetch when user switches back to the tab
const onVisibilityChange = () => {
  if (document.visibilityState === 'visible') {
    void fetchCount();
  }
};

onMounted(() => {
  document.addEventListener('visibilitychange', onVisibilityChange);
});

onUnmounted(() => {
  document.removeEventListener('visibilitychange', onVisibilityChange);
});
</script>
Enter fullscreen mode Exit fullscreen mode

Notice void fetchCount();: explicitly voiding the floating promise in event handlers keeps @typescript-eslint/no-floating-promises satisfied.


4. Cleaner, High-Level Testing in Vitest

Because axios is no longer imported by the component, PendingSubmissionsPill.spec.ts mocks the domain function fetchSubmissionsCount directly using vi.mocked():

import type { VueWrapper } from '@vue/test-utils';
import { flushPromises, shallowMount } from '@vue/test-utils';
import { fetchSubmissionsCount } from '~/api/submissions';
import { useSubmissionsRefresh } from '~/common/useSubmissionsRefresh';
import { createAxiosError, createVueData } from '~/spec/mockFactories';
import PendingSubmissionsPill from './PendingSubmissionsPill.vue';

vi.mock('~/api/submissions');

describe('when tab becomes visible again', () => {
  it('refetches the latest count', async () => {
    createWrapper(3);
    vi.mocked(fetchSubmissionsCount).mockResolvedValue({ count: 7 });

    // Trigger window visibility event
    document.dispatchEvent(new Event('visibilitychange'));
    await flushPromises();

    expect(fetchSubmissionsCount).toHaveBeenCalled();
    expect(wrapper.text()).toContain('7');
  });
});
Enter fullscreen mode Exit fullscreen mode

Tests are no longer concerned with HTTP verbs or URLs—they verify application behavior and user outcomes directly.


Key Takeaways

  1. Extract Network Calls to API Services: Never call axios.get directly in Vue components. Keep components focused on rendering and UI state.
  2. Type API Responses with OpenAPI Contracts: Typing service functions with generated contracts (Promise<GetApiV1SubmissionsCountResponse>) prevents subtle property mismatches.
  3. Mock Domain Functions, Not HTTP Clients: Mocking fetchSubmissionsCount() rather than axios.get('/api/...') makes unit tests clearer, more resilient, and easier to maintain.

Check out the merged Merge Request on GitLab:

👉 GitLab Contributors MR !3201


Author: Manish Kumar

GitLab: @manishpatel00

Top comments (0)