Skip to content

Instantly share code, notes, and snippets.

@brobles82
Created February 25, 2020 16:54
Show Gist options
  • Save brobles82/5d3f97f5f97d547bac42d7ccf1327352 to your computer and use it in GitHub Desktop.
Save brobles82/5d3f97f5f97d547bac42d7ccf1327352 to your computer and use it in GitHub Desktop.
import fs from 'fs'
const fse = require('fs-extra')
const chalk = require('chalk')
const log = console.log
class LoggerManager {
constructor(page, reportFileName) {
this._page = page
this._reportFileName = reportFileName
this._requests = []
}
addLineBreak() {
fse.appendFile(`./src/logs/${this._reportFileName}.log`, '\r\n')
}
addToReport(data) {
this.addLineBreak()
fs.appendFile(`./src/logs/${this._reportFileName}.log`, data, () => {})
this.addLineBreak()
}
saveJsonReport(data) {
this.addLineBreak()
fse.appendFile(
`./src/logs/${this._reportFileName}.log`,
JSON.stringify(data),
)
this.addLineBreak()
}
printDuplicatedRequests() {
const results = [
...this._requests
.reduce((mp, o) => {
const key = JSON.stringify([o.url, o.method, o.data])
if (!mp.has(key)) mp.set(key, {...o, count: 0})
mp.get(key).count++
return mp
}, new Map())
.values(),
]
// eslint-disable-next-line func-names
const dupped = results.filter(function(el) {
return el.count > 1
})
if (dupped.length > 0) {
this.saveJsonReport(dupped)
}
}
startInterceptor() {
try {
fs.unlinkSync(`./src/logs/${this._reportFileName}.log`)
} catch (err) {
log(chalk.blue(`Creating new log for ${this._reportFileName}`))
fse.outputFileSync(`./src/logs/${this._reportFileName}.log`, '')
}
this._page.on('request', interceptedRequest => {
if (interceptedRequest.resourceType() === 'xhr') {
this._requests.push({
url: interceptedRequest.url(),
method: interceptedRequest.method(),
data:
interceptedRequest.postData() == undefined
? ''
: interceptedRequest.postData(),
})
}
if (interceptedRequest.resourceType() === 'image') {
interceptedRequest.abort()
} else {
interceptedRequest.continue()
}
})
this._page.on('pageerror', ({message}) => this.addToReport(message))
}
resetRequests() {
this._requests = []
}
addRequest(request) {
this._requests.push(request)
}
set reportFileName(reportFileName) {
this._reportFileName = reportFileName
}
}
export default LoggerManager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment