Create

The create method will let users create new files with customizable content. It will need one POST route and will accept JSON data containing the filename and the file contents. The following code sample creates the first route, as well as our Polaris middleware , which is executed every time a request comes in:

$polarisPath = [System.IO.Path]::GetTempFileName() -replace '.tmp','Polaris'
git clone https://github.com/powershell/polaris $polarisPath
Import-Module $polarisPath

$middleWare = @"
`$PolarisPath = '$polarisPathFileSvc'
if (-not (Test-Path `$PolarisPath))
{
[void] (New-Item `$PolarisPath -ItemType Directory)
}
if (`$Request.BodyString -ne `$null)
{
`$Request.Body = `$Request.BodyString | ConvertFrom-Json
}
`$Request | Add-Member -Name PolarisPath -Value `$PolarisPath -MemberType NoteProperty
"@

New-PolarisRouteMiddleware -Name JsonBodyParser -ScriptBlock ([scriptblock]::Create($middleWare)) -Force

# Create
New-PolarisPostRoute -Path "/files" -Scriptblock {
if (-not $request.Body.Name -or -not $request.Body.Content)
{
$response.SetStatusCode(501)
$response.Send("File name and file content may not be empty.")
return
}

[void] (New-Item -ItemType File -Path $Request.PolarisPath -Name $request.Body.Name -Value $request.Body.Content)
} -Force

Through the Polaris middleware script block, we ensure that the working directory is set for each request and that the request body is already converted from JSON data.

In our code, we can decide whether or not to process the request in case the body is not properly set. In this case, a 501 error is returned, which we will see in PowerShell later on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset