Skip to content

Commit

Permalink
Extract initFromRecord
Browse files Browse the repository at this point in the history
  • Loading branch information
mnaoumov committed Dec 18, 2024
1 parent c484db3 commit cd36904
Showing 1 changed file with 28 additions and 25 deletions.
53 changes: 28 additions & 25 deletions src/obsidian/Plugin/PluginSettingsBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export class PluginSettingsBase {
* @param data - The data to initialize the settings from.
*/
public constructor(data: unknown) {
this.initFromJson(data);
this.init(data);
}

/**
Expand All @@ -33,22 +33,24 @@ export class PluginSettingsBase {
}

/**
* Initializes the settings from JSON data.
* Determines if the settings should be saved after loading.
*
* @param data - The data to initialize the settings from.
* @returns A boolean indicating whether the settings should be saved after loading.
*/
public initFromJson(data: unknown): void {
if (data === undefined || data === null) {
return;
}
public shouldSaveAfterLoad(): boolean {
return false;
}

if (typeof data !== 'object' || Array.isArray(data)) {
const type = Array.isArray(data) ? 'Array' : typeof data;
console.error(`Invalid data type. Expected Object, got: ${type}`);
return;
}
/**
* Converts the settings to a JSON object.
*
* @returns The settings as a JSON object.
*/
public toJSON(): Record<string, unknown> {
return Object.fromEntries(Object.entries(this));
}

const record = data as Record<string, unknown>;
protected initFromRecord(record: Record<string, unknown>): void {
for (const [key, value] of Object.entries(record)) {
if (key in this) {
this[key as keyof this] = value as this[keyof this];
Expand All @@ -59,20 +61,21 @@ export class PluginSettingsBase {
}

/**
* Determines if the settings should be saved after loading.
* Initializes the settings from JSON data.
*
* @returns A boolean indicating whether the settings should be saved after loading.
* @param data - The data to initialize the settings from.
*/
public shouldSaveAfterLoad(): boolean {
return false;
}
private init(data: unknown): void {
if (data === undefined || data === null) {
return;
}

/**
* Converts the settings to a JSON object.
*
* @returns The settings as a JSON object.
*/
public toJSON(): Record<string, unknown> {
return Object.fromEntries(Object.entries(this));
if (typeof data !== 'object' || Array.isArray(data)) {
const type = Array.isArray(data) ? 'Array' : typeof data;
console.error(`Invalid data type. Expected Object, got: ${type}`);
return;
}

this.initFromRecord(data as Record<string, unknown>);
}
}

0 comments on commit cd36904

Please sign in to comment.