Skip to content

Commit f516a92

Browse files
James TsaiJames Tsai
authored andcommitted
refactor: add function setAccessTokenConfig
1 parent 4aa819e commit f516a92

File tree

3 files changed

+16
-20
lines changed

3 files changed

+16
-20
lines changed

src/command.ts

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import API from '@hackmd/api'
22
import {CliUx, Command} from '@oclif/core'
3-
import fs from 'fs'
43

54
import config from './config'
6-
import {getConfigFilePath} from './utils'
5+
import {setAccessTokenConfig} from './utils'
76

87
export default abstract class HackMDCommand extends Command {
98
async getAPIClient() {
@@ -13,14 +12,7 @@ export default abstract class HackMDCommand extends Command {
1312
try {
1413
await APIClient.getMe()
1514
if (!config.accessToken) {
16-
const configFilePath = getConfigFilePath()
17-
const newConfigFile = require(configFilePath)
18-
newConfigFile.accessToken = token
19-
fs.writeFile(configFilePath, JSON.stringify(newConfigFile, null, 2), function (err) {
20-
if (err) {
21-
throw err
22-
}
23-
})
15+
setAccessTokenConfig(token)
2416
}
2517

2618
return APIClient

src/commands/logout.ts

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import {Flags} from '@oclif/core'
2-
import fs from 'fs'
32

43
import HackMDCommand from '../command'
5-
import {getConfigFilePath} from '../utils'
4+
import {setAccessTokenConfig} from '../utils'
65

76
export default class Logout extends HackMDCommand {
87
static description = 'Login to HackMD server from CLI'
@@ -20,14 +19,7 @@ You've logged out successfully
2019

2120
async run() {
2221
try {
23-
const configFilePath = getConfigFilePath()
24-
const newConfigFile = require(configFilePath)
25-
newConfigFile.accessToken = ''
26-
fs.writeFile(configFilePath, JSON.stringify(newConfigFile, null, 2), function (err) {
27-
if (err) {
28-
throw err
29-
}
30-
})
22+
setAccessTokenConfig('')
3123
this.log("You've logged out successfully")
3224
} catch (err) {
3325
this.error(err)

src/utils.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import fs from 'fs'
12
import {homedir} from 'os'
23
import * as path from 'path'
34

@@ -11,3 +12,14 @@ export function getConfigFilePath() {
1112

1213
return path.join(configDir, 'config.json')
1314
}
15+
16+
export function setAccessTokenConfig(token: string) {
17+
const configFilePath = getConfigFilePath()
18+
const newConfigFile = require(configFilePath)
19+
newConfigFile.accessToken = token
20+
fs.writeFile(configFilePath, JSON.stringify(newConfigFile, null, 2), function (err) {
21+
if (err) {
22+
throw err
23+
}
24+
})
25+
}

0 commit comments

Comments
 (0)