Skip to content

Commit

Permalink
feat(front-import): change to type safe json parse
Browse files Browse the repository at this point in the history
  • Loading branch information
SARDONYX-sard committed Oct 24, 2024
1 parent 68c28e5 commit 7c47112
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 16 deletions.
2 changes: 2 additions & 0 deletions gui/frontend/src/lib/storage/cacheKeys.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/// The reason for the key value pairs is to simplify refactoring of the language server.
/// If we leave them as strings, we cannot automate symbol changes.
import { OBJECT } from '@/lib/object-utils';

const FORM_PUB_CACHE_KEYS_OBJ = {
Expand Down
42 changes: 26 additions & 16 deletions gui/frontend/src/services/api/backup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,38 @@ import { readFile, writeFile } from './fs';

const SETTINGS_FILE_NAME = 'settings';

/** ref: [better-typescript-lib article(ja)](https://zenn.dev/uhyo/articles/better-typescript-lib-v2#better-typescript-lib-%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6) */
function isPropertyAccessible(obj: unknown): obj is Record<string, unknown> {
return obj !== null;
}

export const BACKUP = {
/** @throws Error */
async import() {
async import(): Promise<Cache | null> {
const settings = await readFile(PRIVATE_CACHE_OBJ.importSettingsPath, SETTINGS_FILE_NAME);
if (settings) {
const obj = JSON.parse(settings);

// Validate
for (const key of Object.keys(obj)) {
if (key === PRIVATE_CACHE_OBJ.importSettingsPath) {
continue; // The import path does not need to be overwritten.
}

// Remove invalid settings values
const isInvalidKey = !CACHE_KEYS.some((cacheKey) => cacheKey === key);
if (isInvalidKey) {
delete obj[key];
}
if (settings === null) {
return null;
}

const json = JSON.parse(settings);
if (!isPropertyAccessible(json)) {
return null;
}

// Validate
for (const key of Object.keys(json)) {
if (key === PRIVATE_CACHE_OBJ.importSettingsPath) {
continue; // The import path does not need to be overwritten.
}

return obj as Cache;
// Remove invalid settings values
const isInvalidKey = !CACHE_KEYS.some((cacheKey) => cacheKey === key);
if (isInvalidKey) {
delete json[key];
}
}

return json;
},

/** @throws Json parse Error */
Expand Down

0 comments on commit 7c47112

Please sign in to comment.