Skip to content

Commit

Permalink
feat: adds ability to output to STDOUT
Browse files Browse the repository at this point in the history
  • Loading branch information
moltar authored and nguyentoanit committed Oct 25, 2019
1 parent cb92cc7 commit 9168278
Showing 1 changed file with 38 additions and 12 deletions.
50 changes: 38 additions & 12 deletions test/refresh-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,33 @@ import { join } from 'path'
import { OAuthClient } from '../src/o-auth-client'
import { config } from './config'

/**
* Refresh an access token.
*
* Usage:
*
* By default, will read and write to `.env` in your current working directory.
*
* $> npm run dev:refresh-token
*
* But you can also specify a file manually to read & write:
*
* $> npm run dev:refresh-token .env.dev
*
* You can also write to STDOUT:
*
* $> npm run dev:refresh-token -
*/

const DOTENV_PATH = join(__dirname, '../.env')
const OUTPUT = process.argv[2] || DOTENV_PATH

function isOutputStdout(output: string) {
return output && output === '-'
}

if (!existsSync(DOTENV_PATH)) {
throw new Error('The `.env` file does not exist.')
if (!isOutputStdout(OUTPUT) && !existsSync(OUTPUT)) {
throw new Error(`The "${OUTPUT}" file does not exist.`)
}

const client = new OAuthClient({
Expand All @@ -22,17 +45,20 @@ if (!config.TEST_REFRESH_TOKEN) {
throw new Error('Missing `TEST_REFRESH_TOKEN` environment variable.')
}

const token = client.createToken(config.TEST_ACCESS_TOKEN, config.TEST_REFRESH_TOKEN)

const dotenv = readFileSync(DOTENV_PATH, { encoding: 'utf8' })

token
client
.createToken(config.TEST_ACCESS_TOKEN, config.TEST_REFRESH_TOKEN)
.refresh()
.then(tokens => {
const res = dotenv.replace(
/TEST_ACCESS_TOKEN=(.+?)\n/,
`TEST_ACCESS_TOKEN=${tokens.accessToken}\n`,
)
writeFileSync(DOTENV_PATH, res, { encoding: 'utf8' })
if (isOutputStdout(OUTPUT)) {
process.stdout.write(tokens.accessToken)
} else {
const dotenv = readFileSync(OUTPUT, { encoding: 'utf8' })

const res = dotenv.replace(
/TEST_ACCESS_TOKEN=(.+?)\n/,
`TEST_ACCESS_TOKEN=${tokens.accessToken}\n`,
)
writeFileSync(OUTPUT, res, { encoding: 'utf8' })
}
})
.catch(err => console.error(err))

0 comments on commit 9168278

Please sign in to comment.