From 2f42e52c6e42026fcb733b1fcb3436aa0754b73e Mon Sep 17 00:00:00 2001 From: Devnil434 Date: Thu, 29 Oct 2026 16:36:05 +0530 Subject: [PATCH 1/3] fix: handle HTTP 204 No Content and empty responses in fetchWithCache --- src/services/github.js | 42 ++++++-- src/services/github.test.js | 193 ++++++++++++++++++++++++++++++++++++ 2 files changed, 225 insertions(+), 10 deletions(-) create mode 100644 src/services/github.test.js diff --git a/src/services/github.js b/src/services/github.js index a4180fa8..d5a7843d 100644 --- a/src/services/github.js +++ b/src/services/github.js @@ -52,7 +52,7 @@ export async function cacheClear() { } // Core fetchWithCache -async function fetchWithCache(url, pat) { +export async function fetchWithCache(url, pat) { // L2 check const cached = await cacheGet(url) if (cached) return cached @@ -77,7 +77,13 @@ async function fetchWithCache(url, pat) { if (res.status === 404) throw new Error('NOT_FOUND') if (!res.ok) throw new Error(`HTTP_${res.status}`) - const data = await res.json() + if (res.status === 204) { + cacheSet(url, []) + return [] + } + + const text = await res.text() + const data = text ? JSON.parse(text) : [] cacheSet(url, data) // write-back, non-blocking return data } @@ -92,8 +98,12 @@ export async function fetchRepos(org, repoCount, pat) { for (let page = 1; page <= maxPages; page++) { const url = `https://api.github.com/orgs/${org}/repos?per_page=100&page=${page}&sort=updated` const data = await fetchWithCache(url, pat) - all.push(...data) - if (data.length < 100) break + if (Array.isArray(data)) { + all.push(...data) + if (data.length < 100) break + } else { + break + } } return all } @@ -104,8 +114,12 @@ export async function fetchContributors(org, repo, pat) { for(let page = 1; page<=maxPages ; page++) { const url = `https://api.github.com/repos/${org}/${repo}/contributors?per_page=100&page=${page}` const data = await fetchWithCache(url, pat) - all.push(...data) - if(data.length < 100) break + if (Array.isArray(data)) { + all.push(...data) + if (data.length < 100) break + } else { + break + } } return all } @@ -116,8 +130,12 @@ export async function fetchIssues(org, repo, pat) { for(let page = 1; page<=maxPages ; page++) { const url = `https://api.github.com/repos/${org}/${repo}/issues?state=all&per_page=100&page=${page}` const data = await fetchWithCache(url, pat) - all.push(...data) - if(data.length < 100) break + if (Array.isArray(data)) { + all.push(...data) + if (data.length < 100) break + } else { + break + } } return all } @@ -128,8 +146,12 @@ export async function fetchPulls(org, repo, pat) { for(let page = 1; page<=maxPages ; page++) { const url = `https://api.github.com/repos/${org}/${repo}/pulls?state=all&per_page=100&page=${page}` const data = await fetchWithCache(url, pat) - all.push(...data) - if(data.length < 100) break + if (Array.isArray(data)) { + all.push(...data) + if (data.length < 100) break + } else { + break + } } return all } diff --git a/src/services/github.test.js b/src/services/github.test.js new file mode 100644 index 00000000..52b6fe4d --- /dev/null +++ b/src/services/github.test.js @@ -0,0 +1,193 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { + fetchWithCache, + fetchContributors, + fetchRepos, + fetchIssues, + fetchPulls, + cacheClear, +} from './github' + +describe('github service', () => { + beforeEach(async () => { + vi.restoreAllMocks() + await cacheClear() + }) + + describe('fetchWithCache', () => { + it('returns empty array [] on 204 No Content without crashing on JSON parsing', async () => { + const mockHeaders = new Headers({ + 'x-ratelimit-limit': '5000', + 'x-ratelimit-remaining': '4999', + 'x-ratelimit-used': '1', + 'x-ratelimit-reset': '1800000000', + }) + + global.fetch = vi.fn().mockResolvedValue({ + status: 204, + ok: true, + headers: mockHeaders, + text: vi.fn().mockResolvedValue(''), + json: vi.fn().mockRejectedValue(new SyntaxError('Unexpected end of JSON input')), + }) + + const result = await fetchWithCache('https://api.github.com/repos/org/empty-repo/contributors') + expect(result).toEqual([]) + expect(global.fetch).toHaveBeenCalledTimes(1) + }) + + it('returns empty array [] when response body is empty string', async () => { + const mockHeaders = new Headers({ + 'x-ratelimit-limit': '5000', + 'x-ratelimit-remaining': '4999', + 'x-ratelimit-used': '1', + 'x-ratelimit-reset': '1800000000', + }) + + global.fetch = vi.fn().mockResolvedValue({ + status: 200, + ok: true, + headers: mockHeaders, + text: vi.fn().mockResolvedValue(''), + }) + + const result = await fetchWithCache('https://api.github.com/repos/org/repo/empty-body') + expect(result).toEqual([]) + }) + + it('parses and returns JSON data correctly on standard 200 response', async () => { + const mockHeaders = new Headers({ + 'x-ratelimit-limit': '5000', + 'x-ratelimit-remaining': '4999', + 'x-ratelimit-used': '1', + 'x-ratelimit-reset': '1800000000', + }) + + const payload = [{ id: 1, login: 'octocat', contributions: 42 }] + + global.fetch = vi.fn().mockResolvedValue({ + status: 200, + ok: true, + headers: mockHeaders, + text: vi.fn().mockResolvedValue(JSON.stringify(payload)), + }) + + const result = await fetchWithCache('https://api.github.com/repos/org/repo/contributors-success') + expect(result).toEqual(payload) + }) + + it('throws RATE_LIMIT on HTTP 403', async () => { + const mockHeaders = new Headers() + global.fetch = vi.fn().mockResolvedValue({ + status: 403, + ok: false, + headers: mockHeaders, + }) + + await expect(fetchWithCache('https://api.github.com/rate-limited')).rejects.toThrow('RATE_LIMIT') + }) + + it('throws NOT_FOUND on HTTP 404', async () => { + const mockHeaders = new Headers() + global.fetch = vi.fn().mockResolvedValue({ + status: 404, + ok: false, + headers: mockHeaders, + }) + + await expect(fetchWithCache('https://api.github.com/missing-repo')).rejects.toThrow('NOT_FOUND') + }) + + it('throws HTTP_{status} on unexpected error status codes', async () => { + const mockHeaders = new Headers() + global.fetch = vi.fn().mockResolvedValue({ + status: 500, + ok: false, + headers: mockHeaders, + }) + + await expect(fetchWithCache('https://api.github.com/server-error')).rejects.toThrow('HTTP_500') + }) + }) + + describe('fetchContributors', () => { + it('handles empty repositories (204 No Content) gracefully without throwing SyntaxError or TypeError', async () => { + const mockHeaders = new Headers({ + 'x-ratelimit-limit': '60', + 'x-ratelimit-remaining': '59', + 'x-ratelimit-used': '1', + 'x-ratelimit-reset': '1800000000', + }) + + global.fetch = vi.fn().mockResolvedValue({ + status: 204, + ok: true, + headers: mockHeaders, + text: vi.fn().mockResolvedValue(''), + }) + + const contribs = await fetchContributors('org', 'empty-repo', null) + expect(contribs).toEqual([]) + }) + + it('handles non-array or malformed API responses without throwing TypeError: data is not iterable', async () => { + const mockHeaders = new Headers({ + 'x-ratelimit-limit': '60', + 'x-ratelimit-remaining': '59', + 'x-ratelimit-used': '1', + 'x-ratelimit-reset': '1800000000', + }) + + global.fetch = vi.fn().mockResolvedValue({ + status: 200, + ok: true, + headers: mockHeaders, + text: vi.fn().mockResolvedValue(JSON.stringify({ message: 'Not found' })), + }) + + const contribs = await fetchContributors('org', 'bad-repo', null) + expect(contribs).toEqual([]) + }) + }) + + describe('fetchRepos, fetchIssues, and fetchPulls robustness', () => { + it('fetchRepos gracefully handles 204 or non-array responses', async () => { + const mockHeaders = new Headers() + global.fetch = vi.fn().mockResolvedValue({ + status: 204, + ok: true, + headers: mockHeaders, + text: vi.fn().mockResolvedValue(''), + }) + + const repos = await fetchRepos('org', 0, null) + expect(repos).toEqual([]) + }) + + it('fetchIssues gracefully handles 204 or non-array responses', async () => { + const mockHeaders = new Headers() + global.fetch = vi.fn().mockResolvedValue({ + status: 204, + ok: true, + headers: mockHeaders, + text: vi.fn().mockResolvedValue(''), + }) + + const issues = await fetchIssues('org', 'repo', null) + expect(issues).toEqual([]) + }) + + it('fetchPulls gracefully handles 204 or non-array responses', async () => { + const mockHeaders = new Headers() + global.fetch = vi.fn().mockResolvedValue({ + status: 204, + ok: true, + headers: mockHeaders, + text: vi.fn().mockResolvedValue(''), + }) + + const pulls = await fetchPulls('org', 'repo', null) + expect(pulls).toEqual([]) + }) + }) +}) From c7d8145157b499a4f3965c9f9afe0736fd15fb57 Mon Sep 17 00:00:00 2001 From: Devnil434 Date: Sun, 8 Nov 2026 20:02:59 +0530 Subject: [PATCH 2/3] fix: enhance fetchWithCache to handle various response types and improve contributor pagination tests --- src/services/github.js | 11 +++++++-- src/services/github.test.js | 48 ++++++++++++++++++++++++++++++++++++- src/test/setup.js | 14 ++++++++++- 3 files changed, 69 insertions(+), 4 deletions(-) diff --git a/src/services/github.js b/src/services/github.js index 7cadb799..9e53ad7a 100644 --- a/src/services/github.js +++ b/src/services/github.js @@ -140,8 +140,15 @@ export async function fetchWithCache(url, pat) { return [] } - const text = await res.text() - const data = text ? JSON.parse(text) : [] + let data + if (typeof res.text === 'function') { + const text = await res.text() + data = text ? JSON.parse(text) : [] + } else if (typeof res.json === 'function') { + data = await res.json() + } else { + data = [] + } cacheSet(url, data) // write-back, non-blocking return data } diff --git a/src/services/github.test.js b/src/services/github.test.js index 52b6fe4d..b61e3224 100644 --- a/src/services/github.test.js +++ b/src/services/github.test.js @@ -77,7 +77,9 @@ describe('github service', () => { }) it('throws RATE_LIMIT on HTTP 403', async () => { - const mockHeaders = new Headers() + const mockHeaders = new Headers({ + 'x-ratelimit-remaining': '0', + }) global.fetch = vi.fn().mockResolvedValue({ status: 403, ok: false, @@ -148,6 +150,50 @@ describe('github service', () => { const contribs = await fetchContributors('org', 'bad-repo', null) expect(contribs).toEqual([]) }) + + it('paginates contributors when using a PAT across multiple pages', async () => { + const mockHeaders = new Headers({ + 'x-ratelimit-limit': '5000', + 'x-ratelimit-remaining': '4999', + 'x-ratelimit-used': '1', + 'x-ratelimit-reset': '1800000000', + }) + + const page1 = Array.from({ length: 100 }, (_, i) => ({ id: i + 1, login: `user-${i + 1}` })) + const page2 = [{ id: 101, login: 'user-101' }, { id: 102, login: 'user-102' }] + + global.fetch = vi.fn().mockImplementation(async (url) => { + const page = new URL(url).searchParams.get('page') + if (page === '1') { + return { + status: 200, + ok: true, + headers: mockHeaders, + text: vi.fn().mockResolvedValue(JSON.stringify(page1)), + } + } + if (page === '2') { + return { + status: 200, + ok: true, + headers: mockHeaders, + text: vi.fn().mockResolvedValue(JSON.stringify(page2)), + } + } + return { + status: 200, + ok: true, + headers: mockHeaders, + text: vi.fn().mockResolvedValue('[]'), + } + }) + + const contribs = await fetchContributors('org', 'repo', 'test-pat') + expect(contribs).toHaveLength(102) + expect(contribs).toEqual([...page1, ...page2]) + expect(contribs).toContainEqual(page1[0]) + expect(contribs).toContainEqual(page2[0]) + }) }) describe('fetchRepos, fetchIssues, and fetchPulls robustness', () => { diff --git a/src/test/setup.js b/src/test/setup.js index 4110b522..ef314605 100644 --- a/src/test/setup.js +++ b/src/test/setup.js @@ -2,6 +2,18 @@ import "@testing-library/jest-dom/vitest"; import { afterEach } from "vitest"; import { cleanup } from "@testing-library/react"; +if (typeof globalThis.ResizeObserver === "undefined") { + globalThis.ResizeObserver = class ResizeObserver { + observe() {} + unobserve() {} + disconnect() {} + }; +} + +if (typeof window !== "undefined") { + window.scrollTo = () => {}; +} + afterEach(() => { cleanup(); -}); \ No newline at end of file +}); From 6f21cbefbdc56b57f6e129b6b5da59a0c508531c Mon Sep 17 00:00:00 2001 From: Devnil434 Date: Mon, 9 Nov 2026 22:29:49 +0530 Subject: [PATCH 3/3] fix: improve fetchWithCache to handle empty responses and malformed JSON --- src/services/github.js | 15 +++-- src/services/github.test.js | 109 +++++++++++++++++++++++++++++++++++- 2 files changed, 117 insertions(+), 7 deletions(-) diff --git a/src/services/github.js b/src/services/github.js index 9e53ad7a..aeeba883 100644 --- a/src/services/github.js +++ b/src/services/github.js @@ -135,15 +135,18 @@ export async function fetchWithCache(url, pat) { if (!res.ok) throw new Error(`HTTP_${res.status}`) - if (res.status === 204) { - cacheSet(url, []) - return [] - } - let data if (typeof res.text === 'function') { const text = await res.text() - data = text ? JSON.parse(text) : [] + if (!text) { + data = [] + } else { + try { + data = JSON.parse(text) + } catch { + throw new Error('INVALID_JSON') + } + } } else if (typeof res.json === 'function') { data = await res.json() } else { diff --git a/src/services/github.test.js b/src/services/github.test.js index b61e3224..7b3c2e1b 100644 --- a/src/services/github.test.js +++ b/src/services/github.test.js @@ -1,4 +1,4 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { fetchWithCache, fetchContributors, @@ -8,12 +8,70 @@ import { cacheClear, } from './github' +function installFakeIndexedDB() { + const tables = new Map() + const db = { + createObjectStore() {}, + close() {}, + transaction(storeName) { + let table = tables.get(storeName) + if (!table) { + table = new Map() + tables.set(storeName, table) + } + const tx = { + oncomplete: null, + onerror: null, + onabort: null, + objectStore() { + return { + get(k) { + const req = { result: table.has(k) ? table.get(k) : undefined } + queueMicrotask(() => req.onsuccess && req.onsuccess()) + return req + }, + put(record) { + table.set(record.k, record) + const req = {} + queueMicrotask(() => req.onsuccess && req.onsuccess()) + return req + }, + clear() { + table.clear() + const req = {} + queueMicrotask(() => req.onsuccess && req.onsuccess()) + return req + }, + } + }, + } + queueMicrotask(() => tx.oncomplete && tx.oncomplete()) + return tx + }, + } + vi.stubGlobal('indexedDB', { + open() { + const req = {} + queueMicrotask(() => { + if (req.onupgradeneeded) req.onupgradeneeded({ target: { result: db } }) + if (req.onsuccess) req.onsuccess({ target: { result: db } }) + }) + return req + }, + }) +} + describe('github service', () => { beforeEach(async () => { vi.restoreAllMocks() + installFakeIndexedDB() await cacheClear() }) + afterEach(() => { + vi.unstubAllGlobals() + }) + describe('fetchWithCache', () => { it('returns empty array [] on 204 No Content without crashing on JSON parsing', async () => { const mockHeaders = new Headers({ @@ -110,6 +168,55 @@ describe('github service', () => { await expect(fetchWithCache('https://api.github.com/server-error')).rejects.toThrow('HTTP_500') }) + + it('returns empty array [] on 409 Conflict and caches that result', async () => { + const mockHeaders = new Headers({ + 'x-ratelimit-limit': '5000', + 'x-ratelimit-remaining': '4999', + 'x-ratelimit-used': '1', + 'x-ratelimit-reset': '1800000000', + }) + + global.fetch = vi.fn().mockResolvedValue({ + status: 409, + ok: false, + headers: mockHeaders, + text: vi.fn().mockResolvedValue(''), + json: vi.fn().mockRejectedValue(new SyntaxError('Unexpected end of JSON input')), + }) + + const url = 'https://api.github.com/repos/org/repo-409/contributors' + const first = await fetchWithCache(url) + expect(first).toEqual([]) + expect(global.fetch).toHaveBeenCalledTimes(1) + + const second = await fetchWithCache(url) + expect(second).toEqual([]) + expect(global.fetch).toHaveBeenCalledTimes(1) + }) + + it('rejects with INVALID_JSON on 200 response with malformed JSON and does not cache it', async () => { + const mockHeaders = new Headers({ + 'x-ratelimit-limit': '5000', + 'x-ratelimit-remaining': '4999', + 'x-ratelimit-used': '1', + 'x-ratelimit-reset': '1800000000', + }) + + global.fetch = vi.fn().mockResolvedValue({ + status: 200, + ok: true, + headers: mockHeaders, + text: vi.fn().mockResolvedValue('{"invalid_json":'), + }) + + const url = 'https://api.github.com/repos/org/repo/malformed-json' + await expect(fetchWithCache(url)).rejects.toThrow('INVALID_JSON') + expect(global.fetch).toHaveBeenCalledTimes(1) + + await expect(fetchWithCache(url)).rejects.toThrow('INVALID_JSON') + expect(global.fetch).toHaveBeenCalledTimes(2) + }) }) describe('fetchContributors', () => {