/
UniversalDashboard.Outrest.psm1
118 lines (93 loc) · 2.73 KB
/
UniversalDashboard.Outrest.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
function Out-UDRestApi {
param(
[Parameter(Mandatory, ParameterSetName = "Module")]
[string]$Module,
[Parameter(Mandatory, ParameterSetName = "Command")]
[string]$Command
)
if ($PSCmdlet.ParameterSetName -eq 'Module')
{
Out-UDModuleRestApi -Module $Module
}
if ($PSCmdlet.ParameterSetName -eq 'Command')
{
$CommandDefinition = Get-Command $Command
Out-UDRestEndpoint -CommandDefinition $CommandDefinition
}
}
function Out-UDModuleRestApi {
param(
[Parameter(Mandatory, ParameterSetName = "Module")]
[string]$Module
)
Get-Command -Module $Module | ForEach-Object {
Out-UDRestEndpoint -CommandDefinition $_
}
}
function Out-UDRestEndpoint {
param(
[Parameter(Mandatory)]
$CommandDefinition
)
$RestMethod = ConvertTo-RestMethod -Verb $CommandDefinition.Verb
$CommandDefinition.ParameterSets | ForEach-Object {
$RestUrl = New-RestUrl -ParameterSet $_
$MandatoryParameters = $_.Parameters.Where({$_.IsMandatory})
$Endpoint = ""
if ($MandatoryParameters.Length -gt 0)
{
$paramBlock = "param("
$_.Parameters.Where({$_.IsMandatory}) | ForEach-Object {
$paramBlock += "`$$($_.Name),"
}
$paramBlock = $paramBlock.TrimEnd(',')
$paramBlock += ")`r`n"
$Endpoint += $paramBlock
}
$Endpoint += '
$Parameters = @{}
$PSBoundParameters.Keys | ForEach-Object {
$Parameters[$_] = $PSBoundParameters[$_]
}
$Request.Query.GetEnumerator() | ForEach-Object {
$Parameters[$_.Key] = $_.Value[0]
}
'
$Endpoint += $CommandDefinition.Name + " @Parameters | ConvertTo-Json"
$ScriptBlock = [scriptblock]::Create($Endpoint)
New-UDEndpoint -Url $RestUrl -Method $RestMethod -Endpoint $ScriptBlock
}
}
function New-RestUrl {
param(
[Parameter(Mandatory)]
[System.Management.Automation.CommandParameterSetInfo]$ParameterSet
)
$Url = "/$($CommandDefinition.Noun)"
$ParameterSet.Parameters.Where({$_.IsMandatory}) | ForEach-Object {
$Url += "/:$($_.Name)"
}
$Url
}
function ConvertTo-RestMethod {
param(
[Parameter(Mandatory)]
[string]$Verb
)
$GetVerbs = @('Get')
$PostVerbs = @('Invoke', 'New')
$PutVerbs = @('Set')
$DeleteVerbs = @('Remove')
if ($GetVerbs -contains $Verb) {
return 'GET'
}
if ($PostVerbs -contains $Verb) {
return 'POST'
}
if ($PutVerbs -contains $Verb) {
return 'PUT'
}
if ($DeleteVerbs -contains $Verb) {
return 'DELETE'
}
}