Skip to content

Instantly share code, notes, and snippets.

@codeBelt
Created November 14, 2025 22:20
Show Gist options
  • Select an option

  • Save codeBelt/c32fd3f0ecad3363daf5e2781a24fcec to your computer and use it in GitHub Desktop.

Select an option

Save codeBelt/c32fd3f0ecad3363daf5e2781a24fcec to your computer and use it in GitHub Desktop.
Simple API Mock Code
const urlParams: string = config.params ? `?${new URLSearchParams(config.params).toString()}` : '';
const urlWithParams = url + urlParams;

const requestInit: RequestInit = {
  method: method.toUpperCase(),
  headers: config.headers,
  body: config.body ? JSON.stringify(config.body) : undefined,
};
const response =
    config.useMockData || isFeatureEnabled('enableMockApiData')
      ? await fetchMockData(urlWithParams, requestInit)
      : await fetch(urlWithParams, requestInit);
export async function fetchMockData(url: string, init: RequestInit) {
  const urlObject = new URL(url);

  if (init.method?.toUpperCase() !== 'GET') {
    console.groupCollapsed(`[Mock] ${init.method} Request to ${urlObject.pathname}`);
    if (init.body && typeof init.body === 'string') {
      try {
        console.info('Request Body:', JSON.parse(init.body));
      } catch (_error) {
        console.info('Request Body (non-JSON):', init.body);
      }
    }
    console.groupEnd();
  }

  await delay(1000); // Simulate network delay for mock data

  return fetch(`/mockData/${init.method}${urlObject.pathname}.json`, {headers: init.headers});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment