Skip to content

Commit

Permalink
Fetch data for multiple accounts
Browse files Browse the repository at this point in the history
  • Loading branch information
Corentin Mors committed Jun 30, 2024
1 parent c8bfe08 commit 3e15a54
Show file tree
Hide file tree
Showing 8 changed files with 125 additions and 77 deletions.
91 changes: 34 additions & 57 deletions src/background/endpoints/getLatestDataFromGitLab.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
import * as browser from 'webextension-polyfill';
import { getSettings } from '../utils/getSettings';
import { fetchMRExtraInfo } from '../utils/fetchMRExtraInfo';
import { setBadge } from '../utils/setBadge';

import { removeDuplicateObjectFromArray } from '../../popup/helpers';
import { initGitlabApi } from '../utils/initGitlabApi';
import { MergeRequestSchemaWithBasicLabels } from '@gitbeaker/rest';

export const getLatestDataFromGitLab = async (): Promise<void> => {
console.log('>> POLLING GITLAB API');

const settings = await getSettings();
const gitlabApi = initGitlabApi(settings);
import { IssueSchemaWithBasicLabels, MergeRequestSchemaWithBasicLabels, TodoSchema } from '@gitbeaker/rest';
import { Account } from '../../common/types';
import { MergeRequestsDetails } from '../types';

interface GetLatestDataFromGitLabParams {
account: Account;
}

interface GetLatestDataFromGitLabResponse {
mrReceivedDetails: MergeRequestsDetails[];
mrToReview: number;
mrGivenDetailsNoDraft: MergeRequestsDetails[];
mrReviewed: number;
myDrafts: MergeRequestsDetails[];
issues: IssueSchemaWithBasicLabels[];
todos: TodoSchema[];
}

export const getLatestDataFromGitLab = async (
params: GetLatestDataFromGitLabParams
): Promise<GetLatestDataFromGitLabResponse> => {
const { account } = params;

const gitlabApi = initGitlabApi({ account });
const currentUser = await gitlabApi.Users.showCurrentUser();

/** Fetching MR "To Review" */
Expand Down Expand Up @@ -47,15 +60,15 @@ export const getLatestDataFromGitLab = async (): Promise<void> => {
scope: 'assigned_to_me',
perPage: 100,
maxPages: 5
});
}) as Promise<IssueSchemaWithBasicLabels[]>;

/** Fetching "Todos" */

const todosRequest = gitlabApi.TodoLists.all({
state: 'pending',
perPage: 100,
maxPages: 5
});
}) as Promise<TodoSchema[]>;

const [mrAssigned, mrReceived, mrGiven, issues, todos] = await Promise.all([
mrAssignedRequest,
Expand All @@ -76,13 +89,9 @@ export const getLatestDataFromGitLab = async (): Promise<void> => {
await fetchMRExtraInfo({
gitlabApi,
mrList: requests,
gitlabCE: settings.accounts[0].gitlabCE
gitlabCE: account.gitlabCE
})
).filter(
(mr) =>
settings.accounts[0].draftInToReviewTab ||
(!settings.accounts[0].draftInToReviewTab && !mr.work_in_progress)
);
).filter((mr) => account.draftInToReviewTab || (!account.draftInToReviewTab && !mr.work_in_progress));

let mrToReview = 0;
mrReceivedDetails.forEach((mr) => {
Expand All @@ -94,7 +103,7 @@ export const getLatestDataFromGitLab = async (): Promise<void> => {
const mrGivenDetails = await fetchMRExtraInfo({
gitlabApi,
mrList: mrGiven,
gitlabCE: settings.accounts[0].gitlabCE
gitlabCE: account.gitlabCE
});

const mrGivenDetailsNoDraft = mrGivenDetails.filter((mr) => !mr.work_in_progress);
Expand All @@ -110,45 +119,13 @@ export const getLatestDataFromGitLab = async (): Promise<void> => {

const myDrafts = mrGivenDetails.filter((mr) => mr.work_in_progress);

/** Update alert badge */

const alertBadgeCounters = settings.alertBadgeCounters;
const badgeText = [];
let badgeColor = 'black';

if (alertBadgeCounters.includes(0) && (mrToReview > 0 || alertBadgeCounters.length > 1)) {
badgeText.push(mrToReview);
badgeColor = '#dc3545'; // red
}
if (alertBadgeCounters.includes(1) && (mrReviewed > 0 || alertBadgeCounters.length > 1)) {
badgeText.push(mrReviewed);
badgeColor = '#28a745'; // green
}
if (alertBadgeCounters.includes(2) && (issues.length > 0 || alertBadgeCounters.length > 1)) {
badgeText.push(issues.length);
badgeColor = '#fd7e14'; // orange
}
if (alertBadgeCounters.includes(3) && (todos.length > 0 || alertBadgeCounters.length > 1)) {
badgeText.push(todos.length);
badgeColor = '#1f78d1'; // blue
}

/** Save the fetched data */

const lastUpdateDateUnix = new Date().getTime();

await browser.storage.local.set({
mrReceived: mrReceivedDetails,
return {
mrReceivedDetails,
mrToReview,
mrGiven: mrGivenDetailsNoDraft,
mrGivenDetailsNoDraft,
mrReviewed,
myDrafts,
issues,
todos,
lastUpdateDateUnix
});

await setBadge(badgeText.length > 0 ? badgeText.join('⋅') : '', badgeColor);

return console.log('API Fetched successfully');
todos
};
};
2 changes: 1 addition & 1 deletion src/background/endpoints/getMembersOfGroup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ExpandedMergeRequestSchema, MemberSchema } from '@gitbeaker/rest';

export const getMembersOfGroup = async (groupId: number): Promise<GroupMember[]> => {
const settings = await getSettings();
const gitlabApi = initGitlabApi(settings);
const gitlabApi = initGitlabApi({ account: settings.accounts[0] });
const groupMembers = (await gitlabApi.GroupMembers.all(groupId)) as MemberSchema[];
const groupMembersWithCount = groupMembers.map((member) => {
return { ...member, mergeRequestsCount: 0 };
Expand Down
2 changes: 1 addition & 1 deletion src/background/endpoints/getProjectsList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import { initGitlabApi } from '../utils/initGitlabApi';

export const getProjectsList = async () => {
const settings = await getSettings();
const gitlabApi = initGitlabApi(settings);
const gitlabApi = initGitlabApi({ account: settings.accounts[0] });
return gitlabApi.Groups.all({ minAccessLevel: 30, topLevelOnly: true, perPage: 100 });
};
3 changes: 3 additions & 0 deletions src/background/endpoints/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
export * from './getLatestDataFromGitLab';
export * from './getMembersOfGroup';
export * from './getProjectsList';
export * from './routine';
export * from './setTodoAsDone';
74 changes: 74 additions & 0 deletions src/background/endpoints/routine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import * as browser from 'webextension-polyfill';
import { NoAccountSet } from '../../common/errors';
import { FailFetchSettings } from '../errors';
import { getSettings } from '../utils/getSettings';
import { setBadge } from '../utils/setBadge';
import { getLatestDataFromGitLab } from './getLatestDataFromGitLab';

export const routine = async (): Promise<void> => {
console.log('>> POLLING GITLAB API');

const settings = await getSettings();

if (!settings) {
throw new FailFetchSettings();
}

if (!settings.accounts) {
throw new NoAccountSet();
}

const result = await Promise.all(
settings.accounts.map(async (account) => {
return { accountId: account.address, data: await getLatestDataFromGitLab({ account }) };
})
);

const mrReceivedDetails = result.flatMap((r) => r.data.mrReceivedDetails);
const mrToReview = result.reduce((acc, r) => acc + r.data.mrToReview, 0);
const mrGivenDetailsNoDraft = result.flatMap((r) => r.data.mrGivenDetailsNoDraft);
const mrReviewed = result.reduce((acc, r) => acc + r.data.mrReviewed, 0);
const myDrafts = result.flatMap((r) => r.data.myDrafts);
const issues = result.flatMap((r) => r.data.issues);
const todos = result.flatMap((r) => r.data.todos);

/** Save the fetched data */

const lastUpdateDateUnix = new Date().getTime();

await browser.storage.local.set({
mrReceived: mrReceivedDetails,
mrToReview,
mrGiven: mrGivenDetailsNoDraft,
mrReviewed,
myDrafts,
issues,
todos,
lastUpdateDateUnix
});

/** Update alert badge */

const alertBadgeCounters = settings.alertBadgeCounters;
const badgeText = [];
let badgeColor = 'black';

if (alertBadgeCounters.includes(0) && (mrToReview > 0 || alertBadgeCounters.length > 1)) {
badgeText.push(mrToReview);
badgeColor = '#dc3545'; // red
}
if (alertBadgeCounters.includes(1) && (mrReviewed > 0 || alertBadgeCounters.length > 1)) {
badgeText.push(mrReviewed);
badgeColor = '#28a745'; // green
}
if (alertBadgeCounters.includes(2) && (issues.length > 0 || alertBadgeCounters.length > 1)) {
badgeText.push(issues.length);
badgeColor = '#fd7e14'; // orange
}
if (alertBadgeCounters.includes(3) && (todos.length > 0 || alertBadgeCounters.length > 1)) {
badgeText.push(todos.length);
badgeColor = '#1f78d1'; // blue
}

await setBadge(badgeText.length > 0 ? badgeText.join('⋅') : '', badgeColor);
};
2 changes: 1 addition & 1 deletion src/background/endpoints/setTodoAsDone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const setTodoAsDone = async (id: number | undefined): Promise<void> => {
}

const settings = await getSettings();
const gitlabApi = initGitlabApi(settings);
const gitlabApi = initGitlabApi({ account: settings.accounts[0] });

await gitlabApi.TodoLists.done({ todoId: id });

Expand Down
8 changes: 3 additions & 5 deletions src/background/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import * as browser from 'webextension-polyfill';
import { getLatestDataFromGitLab, setTodoAsDone } from './endpoints';
import { getProjectsList } from './endpoints/getProjectsList';
import { getMembersOfGroup } from './endpoints/getMembersOfGroup';
import { getMembersOfGroup, getProjectsList, routine, setTodoAsDone } from './endpoints';
import { setGlobalError } from '../common/globalError';
import { readConfiguration } from '../common/configuration';

Expand All @@ -15,7 +13,7 @@ readConfiguration<{ refreshRate: number }>(['refreshRate']).then((settings) => {

browser.alarms.onAlarm.addListener(async () => {
try {
await getLatestDataFromGitLab();
await routine();
await setGlobalError(null);
} catch (error) {
if (error instanceof Error) {
Expand All @@ -36,7 +34,7 @@ browser.runtime.onMessage.addListener((message) => {
if (message.type === 'getLatestDataFromGitLab') {
return new Promise(async (resolve) => {
try {
await getLatestDataFromGitLab();
await routine();
await setGlobalError(null);
resolve(true);
} catch (error) {
Expand Down
20 changes: 8 additions & 12 deletions src/background/utils/initGitlabApi.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
import { Gitlab } from '@gitbeaker/rest';
import { GitLabAddressNotSet, GitLabTokenNotSet, NoAccountSet } from '../../common/errors';
import { FailFetchSettings } from '../errors';
import { GetSettingsResponse, GitlabAPI } from '../types';
import { GitLabAddressNotSet, GitLabTokenNotSet } from '../../common/errors';
import { GitlabAPI } from '../types';
import { Account } from '../../common/types';

export const initGitlabApi = (settings: GetSettingsResponse): GitlabAPI => {
if (!settings) {
throw new FailFetchSettings();
}

if (!settings.accounts) {
throw new NoAccountSet();
}
interface InitGitlabApiParams {
account: Account;
}

const account = settings.accounts[0];
export const initGitlabApi = (params: InitGitlabApiParams): GitlabAPI => {
const { account } = params;

if (!account.token || account.token === '') {
throw new GitLabTokenNotSet();
Expand Down

0 comments on commit 3e15a54

Please sign in to comment.