Skip to content

Commit

Permalink
Refactor SettingsManager
Browse files Browse the repository at this point in the history
- remove dependency of EventEmitter
- update Settings Type
  • Loading branch information
Jaewoook committed Aug 10, 2022
1 parent e91f188 commit 0863100
Showing 1 changed file with 15 additions and 16 deletions.
31 changes: 15 additions & 16 deletions src/SettingsManager.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
import { EventEmitter } from "events";
import { getRuntime, merge } from "./utils";
/**
* Internal modules
*/
import { AddressData, SearchKey } from "./AddressManager";
import { isExtension, merge } from "./utils";

export const SETTINGS_KEY_SEARCH_RESULT = "searchResult";
export const SETTINGS_KEY_CACHED_DATA = "addressData";
export const SETTINGS_KEY_PREVIOUS_SEARCH_KEY = "prevSearchKey";

export type Settings = {
searchResult?: {
showEng?: boolean;
showRoad?: boolean;
showLegacy?: boolean;
};
addressData?: AddressData[];
prevSearchKey?: SearchKey;
};
export type Settings = Partial<{
searchResult: Partial<{
showEng: boolean;
showRoad: boolean;
showLegacy: boolean;
}>;
addressData: AddressData[];
prevSearchKey: SearchKey;
}>;

export const DEFAULT_SETTINGS: Settings = {
searchResult: {
Expand All @@ -31,21 +33,18 @@ export const DEFAULT_SETTINGS: Settings = {
},
};

export class SettingsManager<T> extends EventEmitter {
export class SettingsManager<T> {

settings: T | null = null;

constructor(defaultSettings: T) {
super();
(async () => {
try {
this.settings = await this.loadSettings();
} catch (err) {
console.error(err);
this.settings = defaultSettings;
await chrome.storage.local.set(defaultSettings);
} finally {
this.emit("ready");
}
})();
}
Expand All @@ -64,7 +63,7 @@ export class SettingsManager<T> extends EventEmitter {
}

async updateSettings(settings: T) {
if (getRuntime() === "extension") {
if (isExtension()) {
await chrome.storage.local.set(merge(this.settings, settings));
} else {
throw new Error("It works on extension only.");
Expand Down

0 comments on commit 0863100

Please sign in to comment.