CredentialsApi.ps1


Class CredentialsApi : ApiClient {

    CredentialsApi([hashtable]$values) : base ($values) {}

    [PSObject]GetAll() {
        return $this.GetAll(-1, "", "")
    }

    [PSObject]GetAll([int]$limit, [string]$orderBy, [string]$continuationToken) {
        $url = $this.BuildUrl("credentials", $False)
        $url += "?limit=$limit,orderBy=$orderBy,continuationToken=$continuationToken"

        try {
            return $this.Get($url)
        }
        catch {
            throw "Failed to retrieve credentials: $_"
        }
    }

    [string]Create([string]$id, [CredentialTypes]$credentialType, [psobject]$credentialData) {
        $url = $this.BuildUrl("credentials", $False)

        $credentialCreate = @{
            id   = $id
            type = $credentialType.ToString()
        }

        $credentialCreate = $this.AddCredentialData($credentialCreate, $credentialData)

        # Convert the object to JSON to use in the POST body (Note: Default depth is 2 when serializing)
        $json = $credentialCreate | ConvertTo-Json -Depth 10

        # Send the POST
        try {
            LogIt "Posting to $url"
            $response = $this.Post($url, $json)

            $credentialId = $response.id    
            return $credentialId    
        }
        catch {
            throw "Failed to create credentials: $_"
        }
    }
    
    [void]Update([string]$id, [PSObject]$credentialData) {
        $url = $this.BuildUrl("credentials/$id", $False)

        $credentialUpdate = $this.AddCredentialData(@{}, $credentialData)

        # Convert the object to JSON to use in the POST body (Note: Default depth is 2 when serializing)
        $json = $credentialUpdate | ConvertTo-Json -Depth 10

        try {
            $this.Put($url, $json)
        }
        catch {
            throw "Failed to update credentials: $_"
        }        
    }

    [void]Remove([string]$id) {
        LogIt "Deleting credential id $id"

        $url = $this.BuildUrl("credentials/$id", $False)

        try {
            $this.Delete($url)
        }
        catch {
            throw "Failed to delete credential id $($id): $_"
        }        
    }

    hidden [PSObject]AddCredentialData([PSObject]$obj, [psobject]$credentialData)  {
        foreach ($key in $credentialData.Keys) {
            Add-Member -InputObject $obj -NotePropertyName $key -NotePropertyValue $credentialData[$key]
        }

        return $obj
    }
}

Function New-CredentialsApi([hashtable]$values) {
    return [CredentialsApi]::New($values)
}