UNPKG

999 BJavaScriptView Raw
1const os = require('os')
2const path = require('path')
3const fsEx = require('fs-extra')
4
5class UserSettings {
6 constructor () {
7 this.settingsFolder = process.env.USER_PATH ? process.env.USER_PATH : path.join(os.homedir(), '.sgcloud')
8 this.sessionFile = path.join(this.settingsFolder, 'session.json')
9 }
10
11 validate () {
12 this.getToken()
13 return this
14 }
15
16 /**
17 * @returns {String}
18 */
19 getToken () {
20 const data = this._loadSession()
21 if (!data.token) throw new Error('You\'re not logged in! Please run `sgcloud login` again.')
22 return data.token
23 }
24
25 /**
26 * @param {String} token - JWT Session Token
27 * @return {Session}
28 */
29 setToken (token) {
30 const data = this._loadSession()
31 data.token = token
32 fsEx.ensureDirSync(this.settingsFolder)
33 fsEx.writeJsonSync(this.sessionFile, data)
34 return this
35 }
36
37 _loadSession (validate = true) {
38 return fsEx.readJsonSync(this.sessionFile, {throws: false}) || {}
39 }
40}
41
42module.exports = UserSettings