| | | 1 | | |
| | | 2 | | <# |
| | | 3 | | .SYNOPSIS |
| | | 4 | | Checks request validators and writes 304 if appropriate; otherwise sets ETag/Last-Modified. |
| | | 5 | | .DESCRIPTION |
| | | 6 | | Returns $true if a 304 Not Modified was written (you should NOT write a body). |
| | | 7 | | Returns $false if cache missed; in that case the function sets validators on the response and |
| | | 8 | | you should write the fresh body/status yourself. |
| | | 9 | | .PARAMETER Payload |
| | | 10 | | The response payload (string or byte[]) to hash for ETag generation. |
| | | 11 | | If you have a stable payload, use this to get automatic ETag generation. |
| | | 12 | | If you have a dynamic payload, consider using -ETag instead. |
| | | 13 | | .PARAMETER ETag |
| | | 14 | | Explicit ETag token (quotes optional). If supplied, no hashing occurs. |
| | | 15 | | .PARAMETER Weak |
| | | 16 | | Emit a weak ETag (W/"..."). |
| | | 17 | | .PARAMETER LastModified |
| | | 18 | | Optional last-modified timestamp to emit and validate. |
| | | 19 | | .EXAMPLE |
| | | 20 | | if (-not (Test-KrCacheRevalidation -Payload $payload)) { |
| | | 21 | | Write-KrTextResponse -InputObject $payload -StatusCode 200 |
| | | 22 | | } # writes auto-ETag based on payload |
| | | 23 | | .EXAMPLE |
| | | 24 | | if (-not (Test-KrCacheRevalidation -ETag 'v1' -LastModified (Get-Date '2023-01-01'))) { |
| | | 25 | | Write-KrTextResponse -InputObject $payload -StatusCode 200 |
| | | 26 | | } # writes explicit ETag and Last-Modified |
| | | 27 | | #> |
| | | 28 | | function Test-KrCacheRevalidation { |
| | | 29 | | [KestrunRuntimeApi('Route')] |
| | | 30 | | [CmdletBinding()] |
| | | 31 | | [OutputType([bool])] |
| | | 32 | | param( |
| | | 33 | | [Parameter(Mandatory = $true)] |
| | | 34 | | [object]$Payload, |
| | | 35 | | [Parameter()] |
| | | 36 | | [string]$ETag, |
| | | 37 | | [Parameter()] |
| | | 38 | | [switch]$Weak, |
| | | 39 | | [Parameter()] |
| | | 40 | | [DateTimeOffset]$LastModified |
| | | 41 | | ) |
| | | 42 | | |
| | | 43 | | # Only works inside a route script block where $Context is available |
| | 0 | 44 | | if ($null -ne $Context.Response) { |
| | | 45 | | # Call the C# method on the $Context.Response object |
| | 0 | 46 | | $handled = $Context.Response.RevalidateCache( |
| | | 47 | | $Payload, |
| | | 48 | | $ETag, |
| | | 49 | | $Weak.IsPresent, |
| | | 50 | | $LastModified |
| | | 51 | | ) |
| | | 52 | | |
| | 0 | 53 | | return $handled |
| | | 54 | | } else { |
| | 0 | 55 | | Write-KrOutsideRouteWarning |
| | | 56 | | } |
| | | 57 | | } |