Skip to content
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

Use a single local storage key for all elements #120

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions src/background/endpoints/routine.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
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';
import { Storage } from '../../common/storage';

export const routine = async (): Promise<void> => {
console.log('>> POLLING GITLAB API');
Expand Down Expand Up @@ -36,7 +36,7 @@ export const routine = async (): Promise<void> => {

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

await browser.storage.local.set({
await new Storage().setKeys({
mrReceived: mrReceivedDetails,
mrToReview,
mrGiven: mrGivenDetailsNoDraft,
Expand Down
10 changes: 6 additions & 4 deletions src/background/endpoints/setTodoAsDone.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as browser from 'webextension-polyfill';
import { getSettings } from '../utils/getSettings';
import { initGitlabApi } from '../utils/initGitlabApi';
import { TodoSchema } from '@gitbeaker/rest';
import { Storage } from '../../common/storage';

export const setTodoAsDone = async (id: number | undefined): Promise<void> => {
if (!id) {
Expand All @@ -13,11 +13,13 @@ export const setTodoAsDone = async (id: number | undefined): Promise<void> => {

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

const storage = await browser.storage.local.get(['todos']);
const storage = new Storage();

const currentTodos: TodoSchema[] = storage.todos;
const currentTodos: TodoSchema[] = (await storage.getKeys(['todos'])).todos;

const newTodos = id ? currentTodos.filter((todo) => todo.id !== id) : [];

return await browser.storage.local.set({ todos: newTodos });
await storage.setKeys({ todos: newTodos });

return;
};
30 changes: 19 additions & 11 deletions src/common/configuration.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import * as browser from 'webextension-polyfill';
import { Account, Configuration, TabId } from '../common/types';
import { config } from '../config/config';
import { Storage } from './storage';

export const updateConfiguration = async (objectToStore: Record<string, any>): Promise<void> => {
await browser.storage.local.set(objectToStore);
const storage = new Storage();

await storage.setKeys({ configuration: objectToStore });
console.log('Configuration Updated');
};

Expand All @@ -17,21 +19,27 @@ export const updateAccountConfiguration = async (
};

export const readConfiguration = async <T>(keys: string[]): Promise<T> => {
return browser.storage.local.get(keys).then((settings) => {
if (typeof settings.defaultTab === 'number') {
const storage = new Storage();

return storage.getKeys(['configuration']).then(({ configuration }) => {
if (!configuration) {
return config as T;
}

if (typeof configuration.defaultTab === 'number') {
const legacyMapping: { [key: number]: TabId } = {
0: 'to_review',
1: 'under_review',
2: 'issues',
3: 'todo_list'
};
settings.defaultTab = legacyMapping[settings.defaultTab] ?? 'to_review';
configuration.defaultTab = legacyMapping[configuration.defaultTab] ?? 'to_review';
}

if (typeof settings.accounts === 'string') {
const accounts = JSON.parse(settings.accounts);
if (typeof configuration.accounts === 'string') {
const accounts = JSON.parse(configuration.accounts);

settings.accounts =
configuration.accounts =
accounts?.map((account: any) => ({
token: account.token,
address: account.address,
Expand All @@ -42,12 +50,12 @@ export const readConfiguration = async <T>(keys: string[]): Promise<T> => {
}

for (const setting of keys) {
if (settings[setting] === undefined) {
settings[setting] = (config as Record<string, any>)[setting] ?? undefined;
if (configuration[setting] === undefined) {
configuration[setting] = (config as Record<string, any>)[setting] ?? undefined;
}
}

return settings as T;
return configuration as T;
});
};

Expand Down
4 changes: 2 additions & 2 deletions src/common/getLocalData.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as browser from 'webextension-polyfill';
import { getGlobalError } from './globalError';
import { Storage } from './storage';

export const getLocalData = async () => {
const globalError = await getGlobalError();
Expand All @@ -8,7 +8,7 @@ export const getLocalData = async () => {
return Promise.resolve({ error: globalError });
}

return browser.storage.local.get([
return new Storage().getKeys([
'mrReceived',
'mrGiven',
'mrToReview',
Expand Down
11 changes: 7 additions & 4 deletions src/common/globalError.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import * as browser from 'webextension-polyfill';
import { GitLabAddressNotSet, GitLabTokenNotSet, GlobalError } from './errors';
import { setBadge } from '../background/utils/setBadge';
import { Storage } from './storage';

export const setGlobalError = async (error: Error | null) => {
const storage = new Storage();

if (error) {
const globalError = {
name: error.name,
Expand All @@ -14,12 +16,13 @@ export const setGlobalError = async (error: Error | null) => {
error instanceof GitLabAddressNotSet || error instanceof GitLabTokenNotSet ? 'orange' : 'red';
await setBadge('!', badgeColor);

return await browser.storage.local.set({ globalError: JSON.stringify(globalError) });
return await storage.setKeys({ globalError: JSON.stringify(globalError) });
}
return await browser.storage.local.remove('globalError');
return await storage.removeKey('globalError');
};

export const getGlobalError = async (): Promise<GlobalError> => {
const { globalError } = await browser.storage.local.get('globalError');
const storage = new Storage();
const { globalError } = await storage.getKeys(['globalError']);
return globalError ? JSON.parse(globalError) : null;
};
68 changes: 68 additions & 0 deletions src/common/storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import * as browser from 'webextension-polyfill';

enum StorageKeysEnum {
mrReceived = 'mrReceived',
mrToReview = 'mrToReview',
mrGiven = 'mrGiven',
mrReviewed = 'mrReviewed',
myDrafts = 'myDrafts',
issues = 'issues',
todos = 'todos',
lastUpdateDateUnix = 'lastUpdateDateUnix',
globalError = 'globalError',
configuration = 'configuration'
}

type StorageKeys = keyof typeof StorageKeysEnum;

export class Storage {
namespace: 'git-notify';

constructor() {
this.namespace = 'git-notify';

if (!browser.storage.local.get(this.namespace)) {
browser.storage.local.set({ [this.namespace]: JSON.stringify({}) });
}
}

async clear() {
return await browser.storage.local.remove(this.namespace);
}

async getKeys(keys: StorageKeys[]): Promise<Partial<Record<StorageKeys, any>>> {
const storage = await browser.storage.local.get(this.namespace);

if (!storage[this.namespace]) {
return {};
}

return keys.reduce(
(acc, key) => {
acc[key] = storage[this.namespace][key];
return acc;
},
{} as Record<StorageKeys, any>
);
}

async setKeys(data: Partial<Record<StorageKeys, any>>) {
return await browser.storage.local.get(this.namespace).then((storage) => {
console.log('storage', storage);

const parsedStorage = storage[this.namespace] ?? {};

return browser.storage.local.set({ [this.namespace]: { ...parsedStorage, ...data } });
});
}

async removeKey(key: StorageKeys) {
await browser.storage.local.get(this.namespace).then((storage) => {
const parsedStorage = storage[this.namespace] ?? {};

delete parsedStorage[key];

return browser.storage.local.set({ [this.namespace]: parsedStorage });
});
}
}
Loading