| | | 1 | | <# |
| | | 2 | | .SYNOPSIS |
| | | 3 | | Writes an object serialized as CBOR to the HTTP response. |
| | | 4 | | .DESCRIPTION |
| | | 5 | | Converts the provided object to CBOR format and writes it to the response body. The status code and content type |
| | | 6 | | .PARAMETER InputObject |
| | | 7 | | The object to serialize and write to the response. |
| | | 8 | | .PARAMETER StatusCode |
| | | 9 | | The HTTP status code to set for the response. Defaults to 200. |
| | | 10 | | .PARAMETER ContentType |
| | | 11 | | The content type to set for the response. If not specified, defaults to application/cbor |
| | | 12 | | .EXAMPLE |
| | | 13 | | Write-KrCborResponse -InputObject $myObject -StatusCode 200 -ContentType "application/cbor" |
| | | 14 | | Writes the $myObject serialized as CBOR to the response with a 200 status code and |
| | | 15 | | content type "application/cbor". |
| | | 16 | | #> |
| | | 17 | | function Write-KrCborResponse { |
| | | 18 | | [KestrunRuntimeApi('Route')] |
| | | 19 | | [CmdletBinding()] |
| | | 20 | | param( |
| | | 21 | | [Parameter(Mandatory = $true, ValueFromPipeline = $true)] |
| | | 22 | | [object]$InputObject, |
| | | 23 | | [Parameter()] |
| | | 24 | | [int]$StatusCode = 200, |
| | | 25 | | [Parameter()] |
| | | 26 | | [string]$ContentType |
| | | 27 | | ) |
| | | 28 | | begin { |
| | | 29 | | # Collect all piped items |
| | 0 | 30 | | $items = [System.Collections.Generic.List[object]]::new() |
| | | 31 | | } |
| | | 32 | | process { |
| | | 33 | | # Accumulate; no output yet |
| | 0 | 34 | | $items.Add($InputObject) |
| | | 35 | | } |
| | | 36 | | end { |
| | | 37 | | # Only works inside a route script block where $Context is available |
| | 0 | 38 | | if ($null -eq $Context -or $null -eq $Context.Response) { |
| | 0 | 39 | | Write-KrOutsideRouteWarning |
| | | 40 | | return |
| | | 41 | | } |
| | | 42 | | # - single item by default when only one was piped |
| | | 43 | | # - array if multiple items were piped |
| | 0 | 44 | | $payload = if ($items.Count -eq 1) { $items[0] } else { $items.ToArray() } |
| | | 45 | | |
| | | 46 | | # Write the CBOR response |
| | 0 | 47 | | $Context.Response.WriteCborResponse($payload, $StatusCode, $ContentType) |
| | | 48 | | } |
| | | 49 | | } |
| | | 50 | | |