Skip to content

Commit

Permalink
Merge pull request #42 from wicksipedia/add-retry-logic
Browse files Browse the repository at this point in the history
💪 Add retry logic
  • Loading branch information
wicksipedia committed Jun 16, 2023
2 parents 17dd586 + b74b0ed commit 726c313
Show file tree
Hide file tree
Showing 5 changed files with 201 additions and 120 deletions.
8 changes: 8 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ inputs:
description: "Strategy to use when analyzing the page (mobile/desktop)."
required: false
default: mobile
maximumNumberOfRetries:
description: Maximum number of times to call API before failing the action
required: false
default: 3
delayBetweenRetries:
description: Duration in ms to wait before retrying
required: false
default: 3000
outputs:
accessibility:
description: accessibility output
Expand Down
196 changes: 110 additions & 86 deletions dist/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dist/index.js.map

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions src/lighthouseResultScore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/* eslint-disable filenames/match-regex */
export interface LighthouseResultScore {
title: string
score: number
}
110 changes: 77 additions & 33 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,39 @@
import * as core from '@actions/core'
import fetch from 'node-fetch'
import {LighthouseResultScore} from './lighthouseResultScore'

async function run(): Promise<void> {
try {
const queryParams = {
key: core.getInput('key', {required: true}),
url: core.getInput('url', {required: true}),
strategy: core.getInput('strategy'),
categories: core.getMultilineInput('categories').map(x => x.toUpperCase())
}
core.debug(`Query params: ${JSON.stringify(queryParams, null, 2)}`)

const url = new URL(
'https://www.googleapis.com/pagespeedonline/v5/runPagespeed'
)
url.searchParams.append('key', core.getInput('key', {required: true}))
url.searchParams.append('url', core.getInput('url', {required: true}))
url.searchParams.append('strategy', core.getInput('strategy'))
for (const category of core.getMultilineInput('categories')) {
url.searchParams.append('category', category.toUpperCase())
}
core.debug(`URL: ${url.toString()}`)
const url = getPagespeedInsightAPIUrl()

core.info(`Running Page Speed Insights for ${queryParams.url}`)
const response = await fetch(url.toString())
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const data: any = await response.json()
const maximumNumberOfRetries = +core.getInput('maximumNumberOfRetries')
const delayBetweenRetries = +core.getInput('delayBetweenRetries')
let retryCount = 0

const lighthouseResult = data.lighthouseResult
for (const category of Object.values(lighthouseResult.categories)) {
processCategory(category)
while (retryCount < maximumNumberOfRetries) {
if (await getLighthouseResult(url)) {
core.info(
`✅ PageSpeed Insights - Website has been analayzed successfully!`
)
break
}

core.info(
`⚠️ Something went wrong! Retry ${
retryCount + 1
}/${maximumNumberOfRetries} - Reattempting it in ${
delayBetweenRetries / 1000
} secs`
)
retryCount++

if (retryCount < maximumNumberOfRetries) {
await new Promise(resolve => setTimeout(resolve, delayBetweenRetries))
} else {
throw new Error(
'❌ PageSpeed Insights - failed to analayze the Website'
)
}
}
} catch (error) {
if (error instanceof Error) core.setFailed(error.message)
Expand All @@ -38,17 +42,57 @@ async function run(): Promise<void> {

run()

type PagespeedUrl = URL

function getPagespeedInsightAPIUrl(): PagespeedUrl {
const queryParams = {
key: core.getInput('key', {required: true}),
url: core.getInput('url', {required: true}),
strategy: core.getInput('strategy'),
categories: core.getMultilineInput('categories').map(x => x.toUpperCase())
}

core.debug(`Query params: ${JSON.stringify(queryParams, null, 2)}`)

const url = new URL(
'https://www.googleapis.com/pagespeedonline/v5/runPagespeed'
)
url.searchParams.append('key', core.getInput('key', {required: true}))
url.searchParams.append('url', core.getInput('url', {required: true}))
url.searchParams.append('strategy', core.getInput('strategy'))
for (const category of core.getMultilineInput('categories')) {
url.searchParams.append('category', category.toUpperCase())
}
core.debug(`URL: ${url.toString()}`)

return url
}

async function getLighthouseResult(url: URL): Promise<boolean> {
const response = await fetch(url.toString())
if (response.ok) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const data: any = await response.json()

const lighthouseResult = data.lighthouseResult
for (const category of Object.values(
lighthouseResult?.categories as LighthouseResultScore[]
)) {
const title = snakeCase(category.title)
const score = category.score * 100
core.debug(`${title}: ${score}`)
core.setOutput(title, score)
}

return true
}

return false
}

function snakeCase(s: string): string {
return s
.replace(/([a-z])([A-Z])/g, '$1_$2')
.replace(/\s+/g, '_')
.toLowerCase()
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function processCategory(category: any): void {
const title = snakeCase(category.title)
const score = category.score * 100
core.debug(`${title}: ${score}`)
core.setOutput(title, score)
}

0 comments on commit 726c313

Please sign in to comment.