Last active
January 15, 2017 16:19
-
-
Save GendelfLugansk/697757c5327de25d748d9001867e8139 to your computer and use it in GitHub Desktop.
Settings service for node-webkit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* jshint node: true */ | |
//noinspection NpmUsedModulesInstalled | |
import Ember from 'ember'; | |
import ENV from 'your-project-name/config/environment'; | |
import nwENV from 'your-project-name/nw/env'; | |
export default Ember.Service.extend({ | |
nwENV, | |
ENV, | |
flashMessages: Ember.inject.service(), | |
lsKey: 'settings', | |
init() { | |
this._super(...arguments); | |
this._restore(); | |
}, | |
setProperties() { | |
let ret = this._super(...arguments); | |
this._persist(); | |
return ret; | |
}, | |
set() { | |
let ret = this._super(...arguments); | |
this._persist(); | |
return ret; | |
}, | |
_persist() { | |
if (this.get('nwENV.isNodeWebKit')) { | |
let fs = require('fs-extra'); | |
let path = require('path'); | |
let settingsFile = this.get('nwENV.appData') + 'settings.json'; | |
try { | |
fs.accessSync(path.dirname(settingsFile), fs.constants.W_OK); | |
} catch (e) { | |
try { | |
fs.mkdirsSync(path.resolve(path.dirname(settingsFile))); | |
} catch (e) { | |
this.get('flashMessages').warning('Can\'t create a directory for settings. ' + e.toString()); | |
} | |
} | |
try { | |
fs.writeJSONSync(settingsFile, this.getProperties(Object.keys(this)), {spaces: 4}); | |
} catch (e) { | |
this.get('flashMessages').warning('Can\'t save settings. ' + e.toString()); | |
} | |
} else { | |
window.localStorage.setItem(this.get('lsKey'), window.JSON.stringify(this.getProperties(Object.keys(this)))); | |
} | |
}, | |
_restore() { | |
let settings = {}; | |
if (this.get('nwENV.isNodeWebKit')) { | |
let fs = require('fs-extra'); | |
let settingsFile = this.get('nwENV.appData') + 'settings.json'; | |
try { | |
settings = fs.readJSONSync(settingsFile); | |
} catch (e) { | |
} | |
} else { | |
let data = window.localStorage.getItem(this.get('lsKey')); | |
if (data) { | |
try { | |
settings = window.JSON.parse(data); | |
} catch (e) { | |
} | |
} | |
} | |
this.setProperties(Ember.$.extend(true, {}, this.get('ENV.defaultSettings'), settings)); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment