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

Rename local-storage to electron-storage #8310

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -2,82 +2,82 @@ import fs from 'fs';
import path from 'path';
import { afterEach, describe, expect, it, vi } from 'vitest';

import LocalStorage from '../../main/local-storage';
import ElectronStorage from '../../main/electron-storage';

describe('LocalStorage()', () => {
describe('Test electron storage()', () => {
afterEach(() => {
vi.clearAllTimers();
});

it('create directory', () => {
const basePath = `/tmp/insomnia-localstorage-${Math.random()}`;
const basePath = `/tmp/insomnia-electronstorage-${Math.random()}`;

const ls = new LocalStorage(basePath);
expect(ls).toBeInstanceOf(LocalStorage);
const ls = new ElectronStorage(basePath);
expect(ls).toBeInstanceOf(ElectronStorage);

const dir = fs.readdirSync(basePath);
expect(dir.length).toEqual(0);
});

it('does basic operations', () => {
const basePath = `/tmp/insomnia-localstorage-${Math.random()}`;
const localStorage = new LocalStorage(basePath);
const basePath = `/tmp/insomnia-electronstorage-${Math.random()}`;
const electronStorage = new ElectronStorage(basePath);

// Test get and set
localStorage.setItem('foo', 'bar 1');
localStorage.setItem('foo', 'bar');
expect(localStorage.getItem('foo', 'BAD')).toBe('bar');
electronStorage.setItem('foo', 'bar 1');
electronStorage.setItem('foo', 'bar');
expect(electronStorage.getItem('foo', 'BAD')).toBe('bar');

// Test Object storage
localStorage.setItem('obj', {
electronStorage.setItem('obj', {
foo: 'bar',
arr: [1, 2, 3],
});
expect(localStorage.getItem('obj')).toEqual({
expect(electronStorage.getItem('obj')).toEqual({
foo: 'bar',
arr: [1, 2, 3],
});

// Test default values
expect(localStorage.getItem('dne', 'default')).toEqual('default');
expect(localStorage.getItem('dne')).toEqual('default');
expect(electronStorage.getItem('dne', 'default')).toEqual('default');
expect(electronStorage.getItem('dne')).toEqual('default');
});

it('does handles malformed files', () => {
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => { });
const basePath = `/tmp/insomnia-localstorage-${Math.random()}`;
const localStorage = new LocalStorage(basePath);
const basePath = `/tmp/insomnia-electronstorage-${Math.random()}`;
const electronStorage = new ElectronStorage(basePath);

// Assert default is returned on bad JSON
fs.writeFileSync(path.join(basePath, 'key'), '{bad JSON');
expect(localStorage.getItem('key', 'default')).toBe('default');
expect(electronStorage.getItem('key', 'default')).toBe('default');

// Assert that writing our file actually works
fs.writeFileSync(path.join(basePath, 'key'), '{"good": "JSON"}');
expect(localStorage.getItem('key', 'default')).toEqual({
expect(electronStorage.getItem('key', 'default')).toEqual({
good: 'JSON',
});
expect(consoleErrorSpy).toHaveBeenCalled();
});

it('does handles failing to write file', () => {
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => { });
const basePath = `/tmp/insomnia-localstorage-${Math.random()}`;
const localStorage = new LocalStorage(basePath);
const basePath = `/tmp/insomnia-electronstorage-${Math.random()}`;
const electronStorage = new ElectronStorage(basePath);
fs.rmdirSync(basePath);
localStorage.setItem('key', 'value');
electronStorage.setItem('key', 'value');

// Since the above operation failed to write, we should now get back
// the default value
expect(localStorage.getItem('key', 'different')).toBe('different');
expect(electronStorage.getItem('key', 'different')).toBe('different');
expect(consoleErrorSpy).toHaveBeenCalled();
});

it('stores a key', () => {
vi.useFakeTimers();
const basePath = `/tmp/insomnia-localstorage-${Math.random()}`;
const localStorage = new LocalStorage(basePath);
localStorage.setItem('foo', 'bar');
const basePath = `/tmp/insomnia-electronstorage-${Math.random()}`;
const electronStorage = new ElectronStorage(basePath);
electronStorage.setItem('foo', 'bar');

// Force debouncer to flush
vi.runOnlyPendingTimers();
Expand All @@ -92,11 +92,11 @@ describe('LocalStorage()', () => {

it('debounces key sets', () => {
vi.useFakeTimers();
const basePath = `/tmp/insomnia-localstorage-${Math.random()}`;
const localStorage = new LocalStorage(basePath);
localStorage.setItem('foo', 'bar1');
localStorage.setItem('another', 10);
localStorage.setItem('foo', 'bar3');
const basePath = `/tmp/insomnia-electronstorage-${Math.random()}`;
const electronStorage = new ElectronStorage(basePath);
electronStorage.setItem('foo', 'bar1');
electronStorage.setItem('another', 10);
electronStorage.setItem('foo', 'bar3');
expect(fs.readdirSync(basePath).length).toEqual(0);

// Force debouncer to flush
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import fs from 'fs';
import path from 'path';

class LocalStorage {
class ElectronStorage {
_buffer: Record<string, string> = {};
_timeouts: Record<string, NodeJS.Timeout> = {};
_basePath: string | null = null;
Expand All @@ -11,7 +11,7 @@ class LocalStorage {
// Debounce writes on a per key basis
fs.mkdirSync(basePath, { recursive: true });

console.log(`[localstorage] Initialized at ${basePath}`);
console.log(`[ElectronStorage] Initialized at ${basePath}`);
}

setItem<T>(key: string, obj?: T) {
Expand Down Expand Up @@ -39,7 +39,7 @@ class LocalStorage {
try {
return JSON.parse(contents);
} catch (error) {
console.error(`[localstorage] Failed to parse item from LocalStorage: ${error}`);
console.error(`[ElectronStorage] Failed to parse item from electron storage: ${error}`);
return defaultObj;
}
}
Expand All @@ -61,7 +61,7 @@ class LocalStorage {
try {
fs.writeFileSync(path, contents);
} catch (error) {
console.error(`[localstorage] Failed to save to LocalStorage: ${error}`);
console.error(`[ElectronStorage] Failed to save to electron storage: ${error}`);
}
}
}
Expand All @@ -72,4 +72,4 @@ class LocalStorage {
}
}

export default LocalStorage;
export default ElectronStorage;
30 changes: 15 additions & 15 deletions packages/insomnia/src/main/window-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,16 @@ import { docsBase } from '../common/documentation';
import * as log from '../common/log';
import { APP_START_TIME, SentryMetrics } from '../common/sentry';
import { invariant } from '../utils/invariant';
import ElectronStorage from './electron-storage';
import { ipcMainOn } from './ipc/electron';
import LocalStorage from './local-storage';

const DEFAULT_WIDTH = 1280;
const DEFAULT_HEIGHT = 720;
const MINIMUM_WIDTH = 500;
const MINIMUM_HEIGHT = 400;

const browserWindows = new Map<'Insomnia' | 'HiddenBrowserWindow', ElectronBrowserWindow>();
let localStorage: LocalStorage | null = null;
let electronStorage: ElectronStorage | null = null;
let hiddenWindowIsBusy = false;

interface Bounds {
Expand All @@ -50,7 +50,7 @@ interface Bounds {
}

export function init() {
initLocalStorage();
initElectronStorage();
}
const stopAndWaitForHiddenBrowserWindow = async (runningHiddenBrowserWindow: BrowserWindow) => {
return await new Promise<void>(resolve => {
Expand Down Expand Up @@ -741,11 +741,11 @@ function saveBounds() {

// Only save the size if we're not in fullscreen
if (!fullscreen) {
localStorage?.setItem('bounds', browserWindow?.getBounds());
localStorage?.setItem('maximize', browserWindow?.isMaximized());
localStorage?.setItem('fullscreen', false);
electronStorage?.setItem('bounds', browserWindow?.getBounds());
electronStorage?.setItem('maximize', browserWindow?.isMaximized());
electronStorage?.setItem('fullscreen', false);
} else {
localStorage?.setItem('fullscreen', true);
electronStorage?.setItem('fullscreen', true);
}
}

Expand All @@ -755,9 +755,9 @@ function getBounds() {
let maximize = false;

try {
bounds = localStorage?.getItem('bounds', {});
fullscreen = localStorage?.getItem('fullscreen', false);
maximize = localStorage?.getItem('maximize', false);
bounds = electronStorage?.getItem('bounds', {});
fullscreen = electronStorage?.getItem('fullscreen', false);
maximize = electronStorage?.getItem('maximize', false);
} catch (error) {
// This should never happen, but if it does...!
console.error('Failed to parse window bounds', error);
Expand All @@ -776,7 +776,7 @@ const ZOOM_MIN = 0.05;

const getZoomFactor = () => {
try {
return localStorage?.getItem('zoomFactor', ZOOM_DEFAULT);
return electronStorage?.getItem('zoomFactor', ZOOM_DEFAULT);
} catch (error) {
// This should never happen, but if it does...!
console.error('Failed to parse zoomFactor', error);
Expand All @@ -797,12 +797,12 @@ export const setZoom = (transformer: (current: number) => number) => () => {
const actual = Math.min(Math.max(ZOOM_MIN, desired), ZOOM_MAX);

browserWindow.webContents.setZoomLevel(actual);
localStorage?.setItem('zoomFactor', actual);
electronStorage?.setItem('zoomFactor', actual);
};

function initLocalStorage() {
const localStoragePath = path.join(process.env['INSOMNIA_DATA_PATH'] || app.getPath('userData'), 'localStorage');
localStorage = new LocalStorage(localStoragePath);
function initElectronStorage() {
const electronStoragePath = path.join(process.env['INSOMNIA_DATA_PATH'] || app.getPath('userData'), 'localStorage');
electronStorage = new ElectronStorage(electronStoragePath);
}

export function createWindowsAndReturnMain({ firstLaunch }: { firstLaunch?: boolean } = {}) {
Expand Down
Loading