mirror of https://github.com/lukechilds/polar.git
jamaljsr
5 years ago
10 changed files with 142 additions and 14 deletions
@ -0,0 +1 @@ |
|||
export { default as settingsService } from './settingsService'; |
@ -0,0 +1,45 @@ |
|||
import { AppSettings } from 'types'; |
|||
import * as files from 'utils/files'; |
|||
import { settingsService } from './'; |
|||
|
|||
jest.mock('utils/files', () => ({ |
|||
write: jest.fn(), |
|||
read: jest.fn(), |
|||
exists: jest.fn(), |
|||
})); |
|||
|
|||
const filesMock = files as jest.Mocked<typeof files>; |
|||
|
|||
describe('SettingsService', () => { |
|||
let settings: AppSettings; |
|||
|
|||
beforeEach(() => { |
|||
settings = { |
|||
lang: 'en-US', |
|||
showAllNodeVersions: true, |
|||
}; |
|||
}); |
|||
|
|||
it('should save the settings to disk', () => { |
|||
settingsService.save(settings); |
|||
expect(filesMock.write).toBeCalledWith( |
|||
expect.stringContaining('settings.json'), |
|||
expect.stringContaining(`"lang": "en-US"`), |
|||
); |
|||
}); |
|||
|
|||
it('should load the settings from disk', async () => { |
|||
filesMock.exists.mockResolvedValue(true); |
|||
filesMock.read.mockResolvedValue('{ "lang": "en-US" }'); |
|||
const settings = await settingsService.load(); |
|||
expect(settings).toBeDefined(); |
|||
expect(settings && settings.lang).toBe('en-US'); |
|||
expect(filesMock.read).toBeCalledWith(expect.stringContaining('settings.json')); |
|||
}); |
|||
|
|||
it('should return undefined if no settings are saved', async () => { |
|||
filesMock.exists.mockResolvedValue(false); |
|||
const settings = await settingsService.load(); |
|||
expect(settings).toBeUndefined(); |
|||
}); |
|||
}); |
@ -0,0 +1,35 @@ |
|||
import { info } from 'electron-log'; |
|||
import { join } from 'path'; |
|||
import { AppSettings, SettingsInjection } from 'types'; |
|||
import { dataPath } from 'utils/config'; |
|||
import { exists, read, write } from 'utils/files'; |
|||
|
|||
class SettingsService implements SettingsInjection { |
|||
/** |
|||
* Saves the given settings to the file system |
|||
* @param settings the list of settings to save |
|||
*/ |
|||
async save(data: AppSettings) { |
|||
const json = JSON.stringify(data, null, 2); |
|||
const path = join(dataPath, 'settings.json'); |
|||
await write(path, json); |
|||
info(`saved settings to '${path}'`, json); |
|||
} |
|||
|
|||
/** |
|||
* Loads a list of settings from the file system |
|||
*/ |
|||
async load(): Promise<AppSettings | undefined> { |
|||
const path = join(dataPath, 'settings.json'); |
|||
if (await exists(path)) { |
|||
const json = await read(path); |
|||
const data = JSON.parse(json); |
|||
info(`loaded app settings from '${path}'`, data); |
|||
return data; |
|||
} else { |
|||
info(`skipped loading app settings because the file '${path}' doesn't exist`); |
|||
} |
|||
} |
|||
} |
|||
|
|||
export default new SettingsService(); |
Loading…
Reference in new issue