Created
January 29, 2021 05:11
-
-
Save fakhrulhilal/154534873d9e7dc22510849c09830806 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: