Skip to content

feat(api): use conditional requests and fetch all inbox notifications #1414

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

Merged
merged 18 commits into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions src/utils/api/__snapshots__/client.test.ts.snap

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/utils/api/__snapshots__/request.test.ts.snap

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions src/utils/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ export function listNotificationsForAuthenticatedUser(
const url = getGitHubAPIBaseUrl(account.hostname);
url.pathname += 'notifications';
url.searchParams.append('participating', String(settings.participating));

return apiRequestAuth(url.toString() as Link, 'GET', account.token);
return apiRequestAuth(url.toString() as Link, 'GET', account.token, {}, true);
}

/**
Expand Down Expand Up @@ -271,5 +270,7 @@ export async function getLatestDiscussion(
(discussion) => discussion.title === notification.subject.title,
)[0] ?? null
);
} catch (err) {}
} catch (err) {
log.error('Failed to get latest discussion');
}
}
53 changes: 49 additions & 4 deletions src/utils/api/request.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import axios, { type AxiosPromise, type Method } from 'axios';
import axios, {
type AxiosResponse,
type AxiosPromise,
type Method,
} from 'axios';
import log from 'electron-log';
import type { Link, Token } from '../../types';
import { parseNextUrl } from './utils';

export function apiRequest(
url: Link,
Expand All @@ -12,15 +18,54 @@ export function apiRequest(
return axios({ method, url, data });
}

export function apiRequestAuth(
export async function apiRequestAuth(
url: Link,
method: Method,
token: Token,
data = {},
paginated = false,
): AxiosPromise | null {
axios.defaults.headers.common.Accept = 'application/json';
axios.defaults.headers.common.Authorization = `token ${token}`;
axios.defaults.headers.common['Cache-Control'] = 'no-cache';
axios.defaults.headers.common['Content-Type'] = 'application/json';
return axios({ method, url, data });
axios.defaults.headers.common['Cache-Control'] = shouldRequestWithNoCache(url)
? 'no-cache'
: '';

if (!paginated) {
return axios({ method, url, data });
}

let response: AxiosResponse | null = null;
let combinedData = [];

try {
let nextUrl: string | null = url;

while (nextUrl) {
response = await axios({ method, url: nextUrl, data });
combinedData = combinedData.concat(response.data); // Accumulate data

nextUrl = parseNextUrl(response);
}
} catch (error) {
log.error('API request failed:', error);
return null;
}

return {
...response,
data: combinedData,
} as AxiosResponse;
}

function shouldRequestWithNoCache(url: string) {
const parsedUrl = new URL(url);

switch (parsedUrl.pathname) {
case '/notifications':
return true;
default:
return false;
}
}
42 changes: 41 additions & 1 deletion src/utils/api/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import type { AxiosResponse } from 'axios';
import type { Hostname } from '../../types';
import { getGitHubAPIBaseUrl, getGitHubGraphQLUrl } from './utils';
import {
getGitHubAPIBaseUrl,
getGitHubGraphQLUrl,
parseNextUrl,
} from './utils';

describe('utils/api/utils.ts', () => {
describe('getGitHubAPIBaseUrl', () => {
Expand All @@ -25,4 +30,39 @@ describe('utils/api/utils.ts', () => {
expect(result.toString()).toBe('https://github.gitify.io/api/graphql');
});
});

describe('parseNextUrl', () => {
it('should parse next url from link header', () => {
const mockResponse = {
headers: {
link: '<https://api.github.com/notifications?participating=false&page=2>; rel="next", <https://api.github.com/notifications?participating=false&page=2>; rel="last"',
},
};

const result = parseNextUrl(mockResponse as unknown as AxiosResponse);
expect(result.toString()).toBe(
'https://api.github.com/notifications?participating=false&page=2',
);
});

it('should return null if no next url in link header', () => {
const mockResponse = {
headers: {
link: '<https://api.github.com/notifications?participating=false&page=2>; rel="last"',
},
};

const result = parseNextUrl(mockResponse as unknown as AxiosResponse);
expect(result).toBeNull();
});

it('should return null if no link header exists', () => {
const mockResponse = {
headers: {},
};

const result = parseNextUrl(mockResponse as unknown as AxiosResponse);
expect(result).toBeNull();
});
});
});
7 changes: 7 additions & 0 deletions src/utils/api/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { AxiosResponse } from 'axios';
import type { Hostname } from '../../types';
import Constants from '../constants';
import { isEnterpriseServerHost } from '../helpers';
Expand All @@ -22,3 +23,9 @@ export function getGitHubGraphQLUrl(hostname: Hostname): URL {

return url;
}

export function parseNextUrl(response: AxiosResponse): string | null {
const linkHeader = response.headers.link;
const matches = linkHeader?.match(/<([^>]+)>;\s*rel="next"/);
return matches ? matches[1] : null;
}