Skip to content

Commit

Permalink
feat: cleanup plumbing + replace deps with oclif cli-ux helpers (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
ndom91 authored Jul 29, 2021
1 parent 0a72948 commit 636fa9f
Show file tree
Hide file tree
Showing 11 changed files with 123 additions and 182 deletions.
176 changes: 41 additions & 135 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,13 @@
"dependencies": {
"axios": "0.21.1",
"chalk": "4.1.1",
"cli-ux": "5.6.3",
"conf": "8.0.0",
"conf-cli": "0.1.9",
"consola": "2.15.0",
"console.table": "0.10.0",
"moment": "2.29.1",
"open": "7.3.1",
"ora": "5.3.0",
"update-notifier": "5.0.1",
"yaml": "1.10.0"
},
Expand Down
4 changes: 0 additions & 4 deletions sdk/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@ const axios = require('axios')
const endpoints = require('./endpoints')

function init({ api, apiKey, baseURL }) {
if (!apiKey) {
throw new Error('Missing API Key')
}

const Authorization = `Bearer ${apiKey}`

const _api =
Expand Down
4 changes: 1 addition & 3 deletions src/commands/checks.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,11 @@ ChecksCommand.flags = {
char: 'o',
description: 'output type',
default: defaultOutput,
options: ['text', 'json'],
options: ['text', 'table', 'json'],
}),
checkName: flags.string({
char: 'c',
description: 'Check upon which to execute action',
default: defaultOutput,
options: ['text', 'json'],
}),
}

Expand Down
14 changes: 4 additions & 10 deletions src/commands/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@ const consola = require('consola')
const { Command } = require('@oclif/command')
const { account } = require('./../services/api')
const config = require('./../services/config')
const {
// checkTemplate,
defaultCheckTemplate,
settingsTemplate,
} = require('../templates/init')
const { defaultCheckTemplate, settingsTemplate } = require('../templates/init')

class InitCommand extends Command {
static args = [
Expand Down Expand Up @@ -60,12 +56,10 @@ class InitCommand extends Command {
exampleCheckYml
)

consola.success(' Project initialized 🦝🎉 \n')
consola.success(' Project initialized 🎉 \n')
consola.info(' You can now create checks via `checkly checks create`')
consola.info(
' You can now create checks via `checkly checks create` or view'
)
consola.info(
' and adjust the example check generated at `.checkly/checks/example.yml`\n'
' Or play with the example check generated at `.checkly/checks/example.yml`\n'
)
consola.debug(
` Generated @checkly/cli settings and folders at \`${process.cwd()}/.checkly\``
Expand Down
54 changes: 44 additions & 10 deletions src/commands/login.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,59 @@
const consola = require('consola')
const { Command } = require('@oclif/command')
const { Command, flags } = require('@oclif/command')
const { cli } = require('cli-ux')
const chalk = require('chalk')

const raccoon = require('../services/raccoon')
const config = require('../services/config')

const generateMaskedKey = (key) => {
const maskedKey = key.replace(/[a-zA-Z0-9]/g, '*').slice(0, key.length - 4)
const lastFourDigitsKey = key.slice(-4)
return `${maskedKey}${lastFourDigitsKey}`
}

class LoginCommand extends Command {
static args = [
{
static flags = {
apiKey: flags.string({
name: 'apiKey',
required: true,
// required: true,
env: 'CHECKLY_API_KEY',
description:
'Checkly API Key. \nIf you did not have one, create it at: https://app.checklyhq.com/account/api-keys',
},
]
}),
}

async run() {
const { args } = this.parse(LoginCommand)
process.stdout.write(raccoon)
config.set('apiKey', args.apiKey)
const { flags } = this.parse(LoginCommand)

// API Key set in env or passed as flag
if (flags.apiKey || config.get('apiKey')) {
console.log(chalk.cyanBright(raccoon))
consola.log(
`API Key already set (${generateMaskedKey(
flags.apiKey ?? config.get('apiKey')
)})`
)
consola.success(' Welcome to checkly-cli 🦝')
return
}

// Prompt for API Key
const apiKey = await cli.prompt('Please enter your Checkly API Key')

// Basic validation
if (apiKey.length !== 32) {
consola.error('Invalid API Key')
process.exit(1)
}

// Successfully set API Key output
config.set('apiKey', apiKey)
config.set('isInitialized', 'true')
consola.success('Welcome to checkly cli 🦝')
console.log(chalk.blue(raccoon))
consola.success(' Welcome to checkly-cli 🦝')
consola.log(`API Key set (${generateMaskedKey(apiKey)})\n`)
consola.log('You can now run `checkly init` to setup the project!')
}
}

Expand Down
1 change: 0 additions & 1 deletion src/modules/checks/info.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const consola = require('consola')
const { checks } = require('../../services/api')

const { print } = require('../../services/utils')

async function infoCheck(id, { output } = {}) {
Expand Down
4 changes: 2 additions & 2 deletions src/modules/checks/list.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
const consola = require('consola')
const { checks } = require('../../services/api')

const { print } = require('../../services/utils')

async function listChecks({ output } = {}) {
try {
const res = await checks.getAll()

const allChecks = res.data.map(
({ id, name, checkType, frequency, locations, activated }) => ({
id,
name,
checkType,
frequency,
locations,
activated
activated,
})
)

Expand Down
10 changes: 4 additions & 6 deletions src/services/api.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const axios = require('axios')
const ora = require('ora')
const { cli } = require('cli-ux')

const sdk = require('../../sdk')
const config = require('./config')
Expand All @@ -10,25 +10,23 @@ const baseHost = config.get(`${env}.apiUrl`)
const basePath = config.get(`${env}.apiVersion`)
const Authorization = `Bearer ${apiKey}`

let spinner = null

const api = axios.create({
baseURL: `${baseHost}${basePath}`,
headers: { Authorization },
})

api.interceptors.request.use(function (config) {
spinner = ora().start()
cli.action.start('Fetching..')
return config
})

api.interceptors.response.use(
(res) => {
spinner.stop()
cli.action.stop('done')
return res
},
(error) => {
spinner.stop()
cli.action.stop('error!')
return Promise.reject(error)
}
)
Expand Down
10 changes: 4 additions & 6 deletions src/services/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@ const Conf = require('conf')
const consola = require('consola')
const config = new Conf()

const key = process.env.CHECKLY_API_KEY || config.apiKey
const env = process.env.NODE_ENV || config.env
const key = process.env.CHECKLY_API_KEY || config.get('apiKey')
const env = process.env.NODE_ENV || config.get('env')

if (!key) {
if (!key && !process.argv.includes('login')) {
consola.error(
'`CHECKLY_API_KEY` is required, please run `checkly init` to initialise project.'
'`CHECKLY_API_KEY` is required, please run `checkly login` or set the CHECKLY_API_KEY environment variable to setup authentication.'
)
process.exit(1)
}

config.set('apiKey', key)

if (env) {
config.set('env', env)
}
Expand Down
26 changes: 22 additions & 4 deletions src/services/utils.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,40 @@
const consola = require('consola')
require('console.table')
const { cli } = require('cli-ux')

function print(data, { output = 'text', format = 'table', type = 'info' }) {
if (output === 'json') {
process.stdout.write(JSON.stringify(data, null, 2))
consola.log(JSON.stringify(data, null, 2))
return
}

process.stdout.write('\n')

if (format === 'table') {
console.table(data)
cli.table(data, {
id: { header: 'ID' },
name: {},
checkType: { header: 'Check Type' },
frequency: {},
locations: {
get: (row) => row.locations.join(','),
},
activated: {
get: (row) => (row.activated === true ? '✅' : '❌'),
},
})
return
}

if (format === 'text') {
consola.log(
data.map((fields) => Object.values(fields).join(', ')).join('\n')
)
return
}

consola[type](data)
}

module.exports = {
print
print,
}

0 comments on commit 636fa9f

Please sign in to comment.