Skip to content

Instantly share code, notes, and snippets.

@fakhrulhilal
Created January 29, 2021 05:11
Show Gist options
  • Save fakhrulhilal/154534873d9e7dc22510849c09830806 to your computer and use it in GitHub Desktop.
Save fakhrulhilal/154534873d9e7dc22510849c09830806 to your computer and use it in GitHub Desktop.
function ConvertTo-Mockaco {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[object]
$Har,
# Output path to Mockaco Mocks folder
[Parameter(Mandatory=$false)]
[string]
$OutputPath = (Get-Location)
)
Process {
if (-not(Test-Path -Path "$OutputPath\file")) {
New-Item -ItemType Directory -Path "$OutputPath\file" | Out-Null
}
foreach ($Entry in $Har.log.entries) {
$Request = ConvertTo-Request -Entry $Entry
$SuggestedFilename = $Request.SuggestedFilename
$Request.Remove('SuggestedFilename')
$Response = ConvertTo-Response -Entry $Entry -OutputPath $OutputPath
$Metadata = @{
request = $Request
response = $Response
}
$Json = ConvertTo-Json $Metadata
Set-Content -Path (Join-Path -Path $OutputPath -ChildPath $SuggestedFilename) -Value $Json
}
}
}
function ConvertTo-Request {
param (
[object]
$Entry
)
Process {
$Request = $Entry.request
$Uri = [System.Uri]::new($Request.url)
$Filename = [System.IO.Path]::GetFileName($Uri.AbsolutePath)
$Output = @{
method = $Request.method
route = $Uri.AbsolutePath.TrimStart('/')
SuggestedFilename = "$($Filename).json"
}
return $Output
}
}
function ConvertTo-Response {
param (
[object]
$Entry,
[string]
$OutputPath
)
Begin {
$IgnoredHeaders = 'Date', 'Server', 'Accept-Ranges', 'Last-Modified', 'Content-Encoding', 'Content-Length', 'Keep-Alive', 'Connection'
}
Process {
$Uri = [System.Uri]::new($Entry.request.url)
$Filename = [System.IO.Path]::GetFileName($Uri.AbsolutePath)
if ($Entry.response.content.mimeType -like 'text/html*') {
$Filename += ".html"
}
$Output = @{
status = 'OK'
headers = @{}
file = "Mocks/file/$Filename"
}
$ExposedHeaders = $Entry.response.headers | ?{ $IgnoredHeaders -notcontains $_.name }
foreach ($Header in $ExposedHeaders) {
$Output.headers[$Header.name] = $Header.value
}
Set-Content -Path (Join-Path -Path $OutputPath -ChildPath "file\$Filename") -Value $Entry.response.content.text
return $Output
}
}
@fakhrulhilal
Copy link
Author

Usage example:

Get-Content -Path 'C:\path\to\url_Archive `[21-01-22 09-46-54`].har' | Out-String | ConvertFrom-Json | ConvertTo-Mockaco -OutputPath 'C:\path\to\Mockaco\Mocks'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment