Skip to content

Commit

Permalink
refactor: move fields down to child function
Browse files Browse the repository at this point in the history
  • Loading branch information
haricnugraha committed Apr 16, 2024
1 parent ebed302 commit 9e09490
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 43 deletions.
6 changes: 0 additions & 6 deletions src/components/probe/prober/http/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
* SOFTWARE. *
**********************************************************************************/

import { monikaFlagsDefaultValue } from '../../../../flag'
import { BaseProber, NotificationType, type ProbeParams } from '..'
import { getContext } from '../../../../context'
import events from '../../../../events'
Expand Down Expand Up @@ -57,11 +56,6 @@ export class HTTPProber extends BaseProber {
responses.push(
// eslint-disable-next-line no-await-in-loop
await httpRequest({
isVerbose: getContext().flags.verbose,
maxRedirects:
getContext().flags['follow-redirects'] ||
monikaFlagsDefaultValue['follow-redirects'],
isEnableFetch: getContext().flags['native-fetch'],
requestConfig: { ...requestConfig, signal },
responses,
})
Expand Down
26 changes: 15 additions & 11 deletions src/components/probe/prober/http/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { expect } from '@oclif/test'
import { HttpResponse, http } from 'msw'
import { setupServer } from 'msw/node'

import { getContext, resetContext, setContext } from '../../../../context'
import type {
ProbeRequestResponse,
RequestConfig,
Expand All @@ -38,9 +39,14 @@ describe('probingHTTP', () => {
describe('httpRequest function', () => {
before(() => {
server.listen()
setContext({
...getContext(),
flags: { ...getContext().flags, 'follow-redirects': 0 },
})
})
afterEach(() => {
server.resetHandlers()
resetContext()
})
after(() => {
server.close()
Expand Down Expand Up @@ -93,7 +99,6 @@ describe('probingHTTP', () => {
try {
// eslint-disable-next-line no-await-in-loop
const resp = await httpRequest({
maxRedirects: 0,
requestConfig: request,
responses,
})
Expand Down Expand Up @@ -142,7 +147,6 @@ describe('probingHTTP', () => {
}

const result = await httpRequest({
maxRedirects: 0,
requestConfig: request,
responses: [],
})
Expand Down Expand Up @@ -182,7 +186,6 @@ describe('probingHTTP', () => {

// act
const res = await httpRequest({
maxRedirects: 0,
requestConfig: request,
responses: [],
})
Expand Down Expand Up @@ -226,7 +229,6 @@ describe('probingHTTP', () => {

// act
const res = await httpRequest({
maxRedirects: 0,
requestConfig: request,
responses: [],
})
Expand Down Expand Up @@ -270,7 +272,6 @@ describe('probingHTTP', () => {

// act
const res = await httpRequest({
maxRedirects: 0,
requestConfig: request,
responses: [],
})
Expand Down Expand Up @@ -314,7 +315,6 @@ describe('probingHTTP', () => {

// act
const res = await httpRequest({
maxRedirects: 0,
requestConfig: request,
responses: [],
})
Expand All @@ -325,6 +325,13 @@ describe('probingHTTP', () => {

it('Should handle HTTP redirect with axios', async () => {
// arrange
setContext({
...getContext(),
flags: {
...getContext().flags,
'follow-redirects': 3,
},
})
server.use(
http.get(
'https://example.com/get',
Expand Down Expand Up @@ -355,11 +362,10 @@ describe('probingHTTP', () => {
method: 'GET',
body: '',
timeout: 10_000,
followRedirects: 3,
}

const res = await httpRequest({
isEnableFetch: true,
maxRedirects: 3,
requestConfig,
responses: [],
})
Expand Down Expand Up @@ -398,11 +404,10 @@ describe('probingHTTP', () => {
method: 'GET',
body: '',
timeout: 10_000,
followRedirects: 3,
}

const res = await httpRequest({
isEnableFetch: false,
maxRedirects: 3,
requestConfig,
responses: [],
})
Expand Down Expand Up @@ -446,7 +451,6 @@ describe('probingHTTP', () => {

// act
const res = await httpRequest({
maxRedirects: 0,
requestConfig: request,
responses: [],
})
Expand Down
43 changes: 17 additions & 26 deletions src/components/probe/prober/http/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,34 +24,30 @@

import * as Handlebars from 'handlebars'
import FormData from 'form-data'
import Joi from 'joi'
// eslint-disable-next-line no-restricted-imports
import * as qs from 'querystring'
import { errors as undiciErrors } from 'undici'
import YAML from 'yaml'
import {
type ProbeRequestResponse,
type RequestConfig,
probeRequestResult,
} from '../../../../interfaces/request'

// eslint-disable-next-line no-restricted-imports
import * as qs from 'querystring'

import { getContext } from '../../../../context'
import { icmpRequest } from '../icmp/request'
import registerFakes from '../../../../utils/fakes'
import { sendHttpRequest, sendHttpRequestFetch } from '../../../../utils/http'
import { log } from '../../../../utils/pino'
import { AxiosError } from 'axios'
import { getErrorMessage } from '../../../../utils/catch-error-handler'
import { errors as undiciErrors } from 'undici'
import Joi from 'joi'

// Register Handlebars helpers
registerFakes(Handlebars)

type probingParams = {
maxRedirects: number
requestConfig: Omit<RequestConfig, 'saveBody' | 'alert'> // is a config object
responses: Array<ProbeRequestResponse> // an array of previous responses
isVerbose?: boolean
isEnableFetch?: boolean
}

const UndiciErrorValidator = Joi.object({
Expand All @@ -64,11 +60,8 @@ const UndiciErrorValidator = Joi.object({
* @returns ProbeRequestResponse, response to the probe request
*/
export async function httpRequest({
maxRedirects,
requestConfig,
responses,
isEnableFetch,
isVerbose,
}: probingParams): Promise<ProbeRequestResponse> {
// Compile URL using handlebars to render URLs that uses previous responses data
const {
Expand Down Expand Up @@ -107,24 +100,22 @@ export async function httpRequest({
}

// Do the request using compiled URL and compiled headers (if exists)
if (isEnableFetch) {
if (getContext().flags['native-fetch']) {
return await probeHttpFetch({
startTime,
isVerbose,
maxRedirects: followRedirects,
renderedURL,
requestParams: { ...newReq, headers: requestHeaders },
allowUnauthorized,
followRedirects,
})
}

return await probeHttpAxios({
startTime,
maxRedirects,
maxRedirects: followRedirects,
renderedURL,
requestParams: { ...newReq, headers: requestHeaders },
allowUnauthorized,
followRedirects,
})
} catch (error: unknown) {
const responseTime = Date.now() - startTime
Expand Down Expand Up @@ -243,29 +234,30 @@ async function probeHttpFetch({
renderedURL,
requestParams,
allowUnauthorized,
isVerbose,
followRedirects,
maxRedirects,
}: {
startTime: number
renderedURL: string
allowUnauthorized: boolean | undefined
isVerbose?: boolean
maxRedirects: number
requestParams: {
method: string | undefined
headers: Headers | undefined
timeout: number
body: string | object
ping: boolean | undefined
}
followRedirects: number
}): Promise<ProbeRequestResponse> {
if (isVerbose) log.info(`Probing ${renderedURL} with Node.js fetch`)
if (getContext().flags.verbose) {
log.info(`Probing ${renderedURL} with Node.js fetch`)
}

const response = await sendHttpRequestFetch({
...requestParams,
allowUnauthorizedSsl: allowUnauthorized,
keepalive: true,
url: renderedURL,
maxRedirects: followRedirects,
maxRedirects,
body:
typeof requestParams.body === 'string'
? requestParams.body
Expand Down Expand Up @@ -310,22 +302,21 @@ type ProbeHTTPAxiosParams = {
body: string | object
ping: boolean | undefined
}
followRedirects: number
}

async function probeHttpAxios({
startTime,
renderedURL,
requestParams,
allowUnauthorized,
followRedirects,
maxRedirects,
}: ProbeHTTPAxiosParams): Promise<ProbeRequestResponse> {
const resp = await sendHttpRequest({
...requestParams,
allowUnauthorizedSsl: allowUnauthorized,
keepalive: true,
url: renderedURL,
maxRedirects: followRedirects,
maxRedirects,
body:
typeof requestParams.body === 'string'
? requestParams.body
Expand Down

0 comments on commit 9e09490

Please sign in to comment.