Skip to content

Commit

Permalink
Refactor: Separate flag handlers (hyperjumptech#1277)
Browse files Browse the repository at this point in the history
* refactor: combine all the flags related code into a file

* refactor: combine handle for logs, flush, and summary flag into one file

* refactor: replace magic numbers with constant

* refactor: remove unnecessary code

* test: adjust test
  • Loading branch information
haricnugraha committed Apr 19, 2024
1 parent 651cdbe commit 95e46b4
Show file tree
Hide file tree
Showing 14 changed files with 633 additions and 610 deletions.
411 changes: 109 additions & 302 deletions src/commands/monika.ts

Large diffs are not rendered by default.

5 changes: 1 addition & 4 deletions src/components/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import isUrl from 'is-url'
import events from '../../events'
import type { Config } from '../../interfaces/config'
import { getContext, setContext } from '../../context'
import { monikaFlagsDefaultValue } from '../../flag'
import type { MonikaFlags } from '../../flag'
import { getEventEmitter } from '../../utils/events'
import { md5Hash } from '../../utils/hash'
Expand Down Expand Up @@ -146,9 +145,7 @@ async function watchConfigsChange(flags: MonikaFlags) {
flags.config.map((source, index) =>
watchConfigChange({
flags,
interval:
flags['config-interval'] ||
monikaFlagsDefaultValue['config-interval'],
interval: flags['config-interval'],
source,
type: 'monika',
index,
Expand Down
16 changes: 11 additions & 5 deletions src/components/logger/flush.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,15 @@
* SOFTWARE. *
**********************************************************************************/

import sinon from 'sinon'
import { type SinonStub, assert, stub } from 'sinon'
import { getContext, resetContext, setContext } from '../../context'
import * as history from './history'
import { flush } from './flush'

let flushAllLogsStub: sinon.SinonStub
let flushAllLogsStub: SinonStub

beforeEach(() => {
flushAllLogsStub = sinon.stub(history, 'flushAllLogs').resolves()
flushAllLogsStub = stub(history, 'flushAllLogs').resolves()
})

afterEach(() => {
Expand All @@ -39,11 +40,16 @@ afterEach(() => {
describe('Flush command', () => {
describe('Force', () => {
it('should flush records without asking for confirmation', async () => {
// arrange
setContext({ flags: { ...getContext().flags, force: true } })

// act
await flush(true)
await flush()

// assert
sinon.assert.calledOnce(flushAllLogsStub)
assert.calledOnce(flushAllLogsStub)

resetContext()
})
})
})
31 changes: 14 additions & 17 deletions src/components/logger/flush.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
import { ux } from '@oclif/core'
import { flushAllLogs } from './history'
import { getContext } from '../../context'
import { log } from '../../utils/pino'
import { flushAllLogs, openLogfile } from './history'

export async function flush(isForce: boolean): Promise<void> {
if (isForce) {
await flushAllLogs()
log.info('Records flushed, thank you.')
export async function flush(): Promise<void> {
if (!getContext().flags.force) {
const answer = await ux.ux.prompt(
'Are you sure you want to flush all logs in monika-logs.db (Y/n)?'
)

return
}

const ans = await ux.ux.prompt(
'Are you sure you want to flush all logs in monika-logs.db (Y/n)?'
)

if (ans === 'Y') {
await flushAllLogs()
log.info('Records flushed, thank you.')
if (answer !== 'Y') {
log.info('Cancelled. Thank you.')

return
return
}
}

log.info('Cancelled. Thank you.')
await openLogfile()
await flushAllLogs()
log.info('Records flushed, thank you.')
}
5 changes: 0 additions & 5 deletions src/components/logger/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import { ProbeRequestResponse } from '../../interfaces/request'
import { Probe } from '../../interfaces/probe'
import type { Notification } from '@hyperjumptech/monika-notification'
import { log } from '../../utils/pino'
import { getConfig } from '../config'
import { getErrorMessage } from '../../utils/catch-error-handler'
const sqlite3 = verboseSQLite()
const dbPath = path.resolve(process.cwd(), 'monika-logs.db')
Expand Down Expand Up @@ -84,7 +83,6 @@ export type DeleteProbeRes = {
}

type Summary = {
numberOfProbes: number
numberOfIncidents: number
numberOfRecoveries: number
numberOfSentNotifications: number
Expand Down Expand Up @@ -558,10 +556,7 @@ export async function getSummary(): Promise<Summary> {
0
)

const config = getConfig()

return {
numberOfProbes: config?.probes?.length || 0,
numberOfIncidents,
numberOfRecoveries,
numberOfSentNotifications,
Expand Down
42 changes: 22 additions & 20 deletions src/components/logger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,35 @@
**********************************************************************************/

import chalk from 'chalk'
import { getAllLogs } from './history'
import { log } from '../../utils/pino'
import { getAllLogs, openLogfile } from './history'

// printAllLogs dumps the content of monika-logs.db onto the screen
export async function printAllLogs(): Promise<void> {
await openLogfile()
const data = await getAllLogs()

for (const {
id,
probeId,
requestUrl,
responseStatus,
responseTime,
} of data) {
log.info(
`${id} id: ${probeId} responseCode: ${chalk.keyword(
getStatusColor(responseStatus)
)(String(responseStatus))} - ${requestUrl}, ${responseTime || '- '}ms`
)
}
}

/**
* getStatusColor colorizes different statusCode
* @param {any} responseCode is the httpStatus to colorize
* @returns {string} color code based on chalk: Chalk & { supportsColor: ColorSupport };
*/
function getStatusColor(responseCode: number) {
function getStatusColor(responseCode: number): string {
switch (Math.trunc(responseCode / 100)) {
case 2: {
return 'cyan'
Expand All @@ -50,21 +70,3 @@ function getStatusColor(responseCode: number) {

return 'white'
}

/**
* printAllLogs dumps the content of monika-logs.db onto the screen
* @returns Promise<void>
*/
export async function printAllLogs(): Promise<void> {
const data = await getAllLogs()

for (const row of data) {
log.info(
`${row.id} id: ${row.probeId} responseCode: ${chalk.keyword(
getStatusColor(row.responseStatus)
)(String(row.responseStatus))} - ${row.requestUrl}, ${
row.responseTime || '- '
}ms`
)
}
}
Loading

0 comments on commit 95e46b4

Please sign in to comment.