-
-
Notifications
You must be signed in to change notification settings - Fork 91
/
OpenApi.ps1
3742 lines (3050 loc) · 131 KB
/
OpenApi.ps1
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Enables the OpenAPI default route in Pode.
.DESCRIPTION
Enables the OpenAPI default route in Pode, as well as setting up details like Title and API Version.
.PARAMETER Path
An optional custom route path to access the OpenAPI definition. (Default: /openapi)
.PARAMETER Title
The Title of the API. (Deprecated - Use Add-PodeOAInfo)
.PARAMETER Version
The Version of the API. (Deprecated - Use Add-PodeOAInfo)
The OpenAPI Specification is versioned using Semantic Versioning 2.0.0 (semver) and follows the semver specification.
https://semver.org/spec/v2.0.0.html
.PARAMETER Description
A short description of the API. (Deprecated - Use Add-PodeOAInfo)
CommonMark syntax MAY be used for rich text representation.
https://spec.commonmark.org/
.PARAMETER OpenApiVersion
Specify OpenApi Version (default: 3.0.3)
.PARAMETER RouteFilter
An optional route filter for routes that should be included in the definition. (Default: /*)
.PARAMETER Middleware
Like normal Routes, an array of Middleware that will be applied to the route.
.PARAMETER EndpointName
The EndpointName of an Endpoint(s) to bind the static Route against.
.PARAMETER Authentication
The name of an Authentication method which should be used as middleware on this Route.
.PARAMETER Role
One or more optional Roles that will be authorised to access this Route, when using Authentication with an Access method.
.PARAMETER Group
One or more optional Groups that will be authorised to access this Route, when using Authentication with an Access method.
.PARAMETER Scope
One or more optional Scopes that will be authorised to access this Route, when using Authentication with an Access method.
.PARAMETER RestrictRoutes
If supplied, only routes that are available on the Requests URI will be used to generate the OpenAPI definition.
.PARAMETER ServerEndpoint
If supplied, will be used as URL base to generate the OpenAPI definition.
The parameter is created by New-PodeOpenApiServerEndpoint
.PARAMETER Mode
Define the way the OpenAPI definition file is accessed, the value can be View or Download. (Default: View)
.PARAMETER NoCompress
If supplied, generate the OpenApi Json version in human readible form.
.PARAMETER MarkupLanguage
Define the default markup language for the OpenApi spec ('Json', 'Json-Compress', 'Yaml')
.PARAMETER EnableSchemaValidation
If supplied enable Test-PodeOAJsonSchemaCompliance cmdlet that provide support for opeapi parameter schema validation
.PARAMETER Depth
Define the default depth used by any JSON,YAML OpenAPI conversion (default 20)
.PARAMETER DisableMinimalDefinitions
If supplied the OpenApi decument will include only the route validated by Set-PodeOARouteInfo. Any other not OpenApi route will be excluded.
.PARAMETER NoDefaultResponses
If supplied, it will disable the default OpenAPI response with the new provided.
.PARAMETER DefaultResponses
If supplied, it will replace the default OpenAPI response with the new provided.(Default: @{'200' = @{ description = 'OK' };'default' = @{ description = 'Internal server error' }} )
.PARAMETER DefinitionTag
A string representing the unique tag for the API specification.
This tag helps distinguish between different versions or types of API specifications within the application.
You can use this tag to reference the specific API documentation, schema, or version that your function interacts with.
.EXAMPLE
Enable-PodeOpenApi -Title 'My API' -Version '1.0.0' -RouteFilter '/api/*'
.EXAMPLE
Enable-PodeOpenApi -Title 'My API' -Version '1.0.0' -RouteFilter '/api/*' -RestrictRoutes
.EXAMPLE
Enable-PodeOpenApi -Path '/docs/openapi' -NoCompress -Mode 'Donwload' -DisableMinimalDefinitions
#>
function Enable-PodeOpenApi {
[CmdletBinding()]
param(
[ValidateNotNullOrEmpty()]
[string]
$Path = '/openapi',
[Parameter(ParameterSetName = 'Deprecated')]
[string]
$Title,
[Parameter(ParameterSetName = 'Deprecated')]
[ValidatePattern('^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$')]
[string]
$Version,
[Parameter(ParameterSetName = 'Deprecated')]
[string]
$Description,
[ValidateSet('3.1.0', '3.0.3', '3.0.2', '3.0.1', '3.0.0')]
[string]
$OpenApiVersion = '3.0.3',
[ValidateNotNullOrEmpty()]
[string]
$RouteFilter = '/*',
[Parameter()]
[string[]]
$EndpointName,
[Parameter()]
[object[]]
$Middleware,
[Parameter()]
[Alias('Auth')]
[string]
$Authentication,
[Parameter()]
[string[]]
$Role,
[Parameter()]
[string[]]
$Group,
[Parameter()]
[string[]]
$Scope,
[switch]
$RestrictRoutes,
[Parameter()]
[ValidateSet('View', 'Download')]
[String]
$Mode = 'view',
[Parameter()]
[ValidateSet('Json', 'Json-Compress', 'Yaml')]
[String]
$MarkupLanguage = 'Json',
[Parameter()]
[switch]
$EnableSchemaValidation,
[Parameter()]
[ValidateRange(1, 100)]
[int]
$Depth = 20,
[Parameter()]
[switch]
$DisableMinimalDefinitions,
[Parameter(Mandatory, ParameterSetName = 'DefaultResponses')]
[hashtable]
$DefaultResponses,
[Parameter(Mandatory, ParameterSetName = 'NoDefaultResponses')]
[switch]
$NoDefaultResponses,
[Parameter()]
[string]
$DefinitionTag
)
if (Test-PodeIsEmpty -Value $DefinitionTag) {
$DefinitionTag = $PodeContext.Server.OpenAPI.SelectedDefinitionTag
}
if ($Description -or $Version -or $Title) {
if (! $Version) {
$Version = '0.0.0'
}
# WARNING: Title, Version, and Description on 'Enable-PodeOpenApi' are deprecated. Please use 'Add-PodeOAInfo' instead
Write-PodeHost $PodeLocale.deprecatedTitleVersionDescriptionWarningMessage -ForegroundColor Yellow
}
if ( $DefinitionTag -ine $PodeContext.Server.Web.OpenApi.DefaultDefinitionTag) {
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag] = Get-PodeOABaseObject
}
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.enableMinimalDefinitions = !$DisableMinimalDefinitions.IsPresent
# initialise openapi info
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].Version = $OpenApiVersion
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].Path = $Path
if ($OpenApiVersion.StartsWith('3.0')) {
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.version = 3.0
}
elseif ($OpenApiVersion.StartsWith('3.1')) {
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.version = 3.1
}
$meta = @{
RouteFilter = $RouteFilter
RestrictRoutes = $RestrictRoutes
NoCompress = ($MarkupLanguage -ine 'Json-Compress')
Mode = $Mode
MarkupLanguage = $MarkupLanguage
DefinitionTag = $DefinitionTag
}
if ( $Title) {
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].info.title = $Title
}
if ($Version) {
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].info.version = $Version
}
if ($Description ) {
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].info.description = $Description
}
if ( $EnableSchemaValidation.IsPresent) {
#Test-Json has been introduced with version 6.1.0
if ($PSVersionTable.PSVersion -ge [version]'6.1.0') {
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.schemaValidation = $EnableSchemaValidation.IsPresent
}
else {
# Schema validation required PowerShell version 6.1.0 or greater
throw ($PodeLocale.schemaValidationRequiresPowerShell610ExceptionMessage)
}
}
if ( $Depth) {
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.depth = $Depth
}
$openApiCreationScriptBlock = {
param($meta)
$format = $WebEvent.Query['format']
$mode = $WebEvent.Query['mode']
$DefinitionTag = $meta.DefinitionTag
if (!$mode) {
$mode = $meta.Mode
}
elseif (@('download', 'view') -inotcontains $mode) {
Write-PodeHtmlResponse -Value "Mode $mode not valid" -StatusCode 400
return
}
if ($WebEvent.path -ilike '*.json') {
if ($format) {
Show-PodeErrorPage -Code 400 -ContentType 'text/html' -Description 'Format query not valid when the file extension is used'
return
}
$format = 'json'
}
elseif ($WebEvent.path -ilike '*.yaml') {
if ($format) {
Show-PodeErrorPage -Code 400 -ContentType 'text/html' -Description 'Format query not valid when the file extension is used'
return
}
$format = 'yaml'
}
elseif (!$format) {
$format = $meta.MarkupLanguage.ToLower()
}
elseif (@('yaml', 'json', 'json-Compress') -inotcontains $format) {
Show-PodeErrorPage -Code 400 -ContentType 'text/html' -Description "Format $format not valid"
return
}
if ($mode -ieq 'download') {
# Set-PodeResponseAttachment -Path
Add-PodeHeader -Name 'Content-Disposition' -Value "attachment; filename=openapi.$format"
}
# generate the openapi definition
$def = Get-PodeOpenApiDefinitionInternal `
-EndpointName $WebEvent.Endpoint.Name `
-DefinitionTag $DefinitionTag `
-MetaInfo $meta
# write the openapi definition
if ($format -ieq 'yaml') {
if ($mode -ieq 'view') {
Write-PodeTextResponse -Value (ConvertTo-PodeYaml -InputObject $def -depth $PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.depth) -ContentType 'application/yaml; charset=utf-8' #Changed to be RFC 9512 compliant
}
else {
Write-PodeYamlResponse -Value $def -Depth $PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.depth
}
}
else {
Write-PodeJsonResponse -Value $def -Depth $PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.depth -NoCompress:$meta.NoCompress
}
}
# add the OpenAPI route
Add-PodeRoute -Method Get -Path $Path -ArgumentList $meta -Middleware $Middleware `
-ScriptBlock $openApiCreationScriptBlock -EndpointName $EndpointName `
-Authentication $Authentication -Role $Role -Scope $Scope -Group $Group
Add-PodeRoute -Method Get -Path "$Path.json" -ArgumentList $meta -Middleware $Middleware `
-ScriptBlock $openApiCreationScriptBlock -EndpointName $EndpointName `
-Authentication $Authentication -Role $Role -Scope $Scope -Group $Group
Add-PodeRoute -Method Get -Path "$Path.yaml" -ArgumentList $meta -Middleware $Middleware `
-ScriptBlock $openApiCreationScriptBlock -EndpointName $EndpointName `
-Authentication $Authentication -Role $Role -Scope $Scope -Group $Group
#set new DefaultResponses
if ($NoDefaultResponses.IsPresent) {
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.defaultResponses = [ordered]@{}
}
elseif ($DefaultResponses) {
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.defaultResponses = $DefaultResponses
}
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.enabled = $true
if ($EndpointName) {
$PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.EndpointName = $EndpointName
}
}
<#
.SYNOPSIS
Creates an OpenAPI Server Object.
.DESCRIPTION
Creates an OpenAPI Server Object.
.PARAMETER Url
A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served.
Variable substitutions will be made when a variable is named in `{`brackets`}`.
.PARAMETER Description
An optional string describing the host designated by the URL. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.
.PARAMETER Variables
A map between a variable name and its value. The value is used for substitution in the server's URL template.
.PARAMETER DefinitionTag
An Array of strings representing the unique tag for the API specification.
This tag helps distinguish between different versions or types of API specifications within the application.
You can use this tag to reference the specific API documentation, schema, or version that your function interacts with.
.EXAMPLE
Add-PodeOAServerEndpoint -Url 'https://myserver.io/api' -Description 'My test server'
.EXAMPLE
Add-PodeOAServerEndpoint -Url '/api' -Description 'My local server'
.EXAMPLE
Add-PodeOAServerEndpoint -Url "https://{username}.gigantic-server.com:{port}/{basePath}" -Description "The production API server" `
-Variable @{
username = @{
default = 'demo'
description = 'this value is assigned by the service provider, in this example gigantic-server.com'
}
port = @{
enum = @('System.Object[]') # Assuming 'System.Object[]' is a placeholder for actual values
default = 8443
}
basePath = @{
default = 'v2'
}
}
}
#>
function Add-PodeOAServerEndpoint {
param (
[Parameter(Mandatory = $true)]
[ValidatePattern('^(https?://|/).+')]
[string]
$Url,
[string]
$Description,
[System.Collections.Specialized.OrderedDictionary]
$Variables,
[string[]]
$DefinitionTag
)
if (Test-PodeIsEmpty -Value $DefinitionTag) {
$DefinitionTag = @($PodeContext.Server.OpenAPI.SelectedDefinitionTag)
}
foreach ($tag in $DefinitionTag) {
if (! $PodeContext.Server.OpenAPI.Definitions[$tag].servers) {
$PodeContext.Server.OpenAPI.Definitions[$tag].servers = @()
}
$lUrl = [ordered]@{url = $Url }
if ($Description) {
$lUrl.description = $Description
}
if ($Variables) {
$lUrl.variables = $Variables
}
$PodeContext.Server.OpenAPI.Definitions[$tag].servers += $lUrl
}
}
<#
.SYNOPSIS
Gets the OpenAPI definition.
.DESCRIPTION
Gets the OpenAPI definition for custom use in routes, or other functions.
.PARAMETER Format
Return the definition in a specific format 'Json', 'Json-Compress', 'Yaml', 'HashTable'
.PARAMETER Title
The Title of the API. (Default: the title supplied in Enable-PodeOpenApi)
.PARAMETER Version
The Version of the API. (Default: the version supplied in Enable-PodeOpenApi)
.PARAMETER Description
A Description of the API. (Default: the description supplied into Enable-PodeOpenApi)
.PARAMETER RouteFilter
An optional route filter for routes that should be included in the definition. (Default: /*)
.PARAMETER RestrictRoutes
If supplied, only routes that are available on the Requests URI will be used to generate the OpenAPI definition.
.PARAMETER DefinitionTag
A string representing the unique tag for the API specification.
This tag helps distinguish between different versions or types of API specifications within the application.
You can use this tag to reference the specific API documentation, schema, or version that your function interacts with.
.EXAMPLE
$defInJson = Get-PodeOADefinition -Json
#>
function Get-PodeOADefinition {
[CmdletBinding()]
param(
[ValidateSet('Json', 'Json-Compress', 'Yaml', 'HashTable')]
[string]
$Format = 'HashTable',
[string]
$Title,
[string]
$Version,
[string]
$Description,
[ValidateNotNullOrEmpty()]
[string]
$RouteFilter = '/*',
[switch]
$RestrictRoutes,
[string]
$DefinitionTag
)
$DefinitionTag = Test-PodeOADefinitionTag -Tag $DefinitionTag
$meta = @{
RouteFilter = $RouteFilter
RestrictRoutes = $RestrictRoutes
}
if ($RestrictRoutes) {
$meta = @{
RouteFilter = $RouteFilter
RestrictRoutes = $RestrictRoutes
}
}
else {
$meta = @{}
}
if ($Title) {
$meta.Title = $Title
}
if ($Version) {
$meta.Version = $Version
}
if ($Description) {
$meta.Description = $Description
}
$oApi = Get-PodeOpenApiDefinitionInternal -MetaInfo $meta -EndpointName $WebEvent.Endpoint.Name -DefinitionTag $DefinitionTag
switch ($Format.ToLower()) {
'json' {
return ConvertTo-Json -InputObject $oApi -Depth $PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.depth
}
'json-compress' {
return ConvertTo-Json -InputObject $oApi -Depth $PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.depth -Compress
}
'yaml' {
return ConvertTo-PodeYaml -InputObject $oApi -depth $PodeContext.Server.OpenAPI.Definitions[$DefinitionTag].hiddenComponents.depth
}
Default {
return $oApi
}
}
}
<#
.SYNOPSIS
Adds a response definition to the supplied route.
.DESCRIPTION
Adds a response definition to the supplied route.
.PARAMETER Route
The route to add the response definition, usually from -PassThru on Add-PodeRoute.
.PARAMETER StatusCode
The HTTP StatusCode for the response.To define a range of response codes, this field MAY contain the uppercase wildcard character `X`.
For example, `2XX` represents all response codes between `[200-299]`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`.
If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code.
.PARAMETER Content
The content-types and schema the response returns (the schema is created using the Property functions).
Alias: ContentSchemas
.PARAMETER Headers
The header name and schema the response returns (the schema is created using Add-PodeOAComponentHeader cmd-let).
Alias: HeaderSchemas
.PARAMETER Description
A Description of the response. (Default: the HTTP StatusCode description)
.PARAMETER Reference
A Reference Name of an existing component response to use.
.PARAMETER Links
A Response link definition
.PARAMETER Default
If supplied, the response will be used as a default response - this overrides the StatusCode supplied.
.PARAMETER PassThru
If supplied, the route passed in will be returned for further chaining.
.PARAMETER DefinitionTag
An Array of strings representing the unique tag for the API specification.
This tag helps distinguish between different versions or types of API specifications within the application.
You can use this tag to reference the specific API documentation, schema, or version that your function interacts with.
.EXAMPLE
Add-PodeRoute -PassThru | Add-PodeOAResponse -StatusCode 200 -Content @{ 'application/json' = (New-PodeOAIntProperty -Name 'userId' -Object) }
.EXAMPLE
Add-PodeRoute -PassThru | Add-PodeOAResponse -StatusCode 200 -Content @{ 'application/json' = 'UserIdSchema' }
.EXAMPLE
Add-PodeRoute -PassThru | Add-PodeOAResponse -StatusCode 200 -Reference 'OKResponse'
#>
function Add-PodeOAResponse {
[CmdletBinding(DefaultParameterSetName = 'Schema')]
[OutputType([hashtable[]])]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[hashtable[]]
$Route,
[Parameter(Mandatory = $true, ParameterSetName = 'Schema')]
[Parameter(Mandatory = $true, ParameterSetName = 'Reference')]
[ValidatePattern('^([1-5][0-9][0-9]|[1-5]XX)$')]
[string]
$StatusCode,
[Parameter(ParameterSetName = 'Schema')]
[Parameter(ParameterSetName = 'SchemaDefault')]
[Alias('ContentSchemas')]
[hashtable]
$Content,
[Alias('HeaderSchemas')]
[AllowEmptyString()]
[ValidateNotNullOrEmpty()]
[ValidateScript({ $_ -is [string] -or $_ -is [string[]] -or $_ -is [hashtable] -or $_ -is [System.Collections.Specialized.OrderedDictionary] })]
$Headers,
[Parameter(Mandatory = $false, ParameterSetName = 'Schema')]
[Parameter(Mandatory = $false, ParameterSetName = 'SchemaDefault')]
[string]
$Description,
[Parameter(Mandatory = $true, ParameterSetName = 'Reference')]
[Parameter(ParameterSetName = 'ReferenceDefault')]
[string]
$Reference,
[Parameter(Mandatory = $true, ParameterSetName = 'ReferenceDefault')]
[Parameter(Mandatory = $true, ParameterSetName = 'SchemaDefault')]
[switch]
$Default,
[Parameter(ParameterSetName = 'Schema')]
[Parameter(ParameterSetName = 'SchemaDefault')]
[System.Collections.Specialized.OrderedDictionary ]
$Links,
[switch]
$PassThru,
[string[]]
$DefinitionTag
)
begin {
# Initialize an array to hold piped-in values
$pipelineValue = @()
}
process {
# Add the current piped-in value to the array
$pipelineValue += $_
}
end {
# Set Route to the array of values
if ($pipelineValue.Count -gt 1) {
$Route = $pipelineValue
}
$DefinitionTag = Test-PodeOADefinitionTag -Tag $DefinitionTag
# override status code with default
if ($Default) {
$code = 'default'
}
else {
$code = "$($StatusCode)"
}
# add the respones to the routes
foreach ($r in @($Route)) {
foreach ($tag in $DefinitionTag) {
if (! $r.OpenApi.Responses.$tag) {
$r.OpenApi.Responses.$tag = [ordered]@{}
}
$r.OpenApi.Responses.$tag[$code] = New-PodeOResponseInternal -DefinitionTag $tag -Params $PSBoundParameters
}
}
if ($PassThru) {
return $Route
}
}
}
<#
.SYNOPSIS
Remove a response definition from the supplied route.
.DESCRIPTION
Remove a response definition from the supplied route.
.PARAMETER Route
The route to remove the response definition, usually from -PassThru on Add-PodeRoute.
.PARAMETER StatusCode
The HTTP StatusCode for the response to remove.
.PARAMETER Default
If supplied, the response will be used as a default response - this overrides the StatusCode supplied.
.PARAMETER PassThru
If supplied, the route passed in will be returned for further chaining.
.EXAMPLE
Add-PodeRoute -PassThru | Remove-PodeOAResponse -StatusCode 200
.EXAMPLE
Add-PodeRoute -PassThru | Remove-PodeOAResponse -StatusCode 201 -Default
#>
function Remove-PodeOAResponse {
[CmdletBinding()]
[OutputType([hashtable[]])]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[hashtable[]]
$Route,
[Parameter(Mandatory = $true)]
[int]
$StatusCode,
[switch]
$Default,
[switch]
$PassThru
)
begin {
# Initialize an array to hold piped-in values
$pipelineValue = @()
}
process {
# Add the current piped-in value to the array
$pipelineValue += $_
}
end {
# Set Route to the array of values
if ($pipelineValue.Count -gt 1) {
$Route = $pipelineValue
}
# override status code with default
$code = "$($StatusCode)"
if ($Default) {
$code = 'default'
}
# remove the respones from the routes
foreach ($r in $Route) {
if ($r.OpenApi.Responses.ContainsKey($code)) {
$null = $r.OpenApi.Responses.Remove($code)
}
}
if ($PassThru) {
return $Route
}
}
}
<#
.SYNOPSIS
Sets the definition of a request for a route.
.DESCRIPTION
Sets the definition of a request for a route.
.PARAMETER Route
The route to set a request definition, usually from -PassThru on Add-PodeRoute.
.PARAMETER Parameters
The Parameter definitions the request uses (from ConvertTo-PodeOAParameter).
.PARAMETER RequestBody
The Request Body definition the request uses (from New-PodeOARequestBody).
.PARAMETER PassThru
If supplied, the route passed in will be returned for further chaining.
.EXAMPLE
Add-PodeRoute -PassThru | Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Schema 'UserIdBody')
#>
function Set-PodeOARequest {
[CmdletBinding()]
[OutputType([hashtable[]])]
param(
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[hashtable[]]
$Route,
[hashtable[]]
$Parameters,
[hashtable]
$RequestBody,
[switch]
$PassThru
)
begin {
# Initialize an array to hold piped-in values
$pipelineValue = @()
}
process {
# Add the current piped-in value to the array
$pipelineValue += $_
}
end {
# Set Route to the array of values
if ($pipelineValue.Count -gt 1) {
$Route = $pipelineValue
}
foreach ($r in $Route) {
if (($null -ne $Parameters) -and ($Parameters.Length -gt 0)) {
$r.OpenApi.Parameters = @($Parameters)
}
if ($null -ne $RequestBody) {
# Only 'POST', 'PUT', 'PATCH' can have a request body
if (('POST', 'PUT', 'PATCH') -inotcontains $r.Method ) {
# {0} operations cannot have a Request Body.
throw ($PodeLocale.getRequestBodyNotAllowedExceptionMessage -f $r.Method)
}
$r.OpenApi.RequestBody = $RequestBody
}
}
if ($PassThru) {
return $Route
}
}
}
<#
.SYNOPSIS
Creates a Request Body definition for routes.
.DESCRIPTION
Creates a Request Body definition for routes from the supplied content-types and schemas.
.PARAMETER Reference
A reference name from an existing component request body.
Alias: Reference
.PARAMETER Content
The content of the request body. The key is a media type or media type range and the value describes it.
For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/*
Alias: ContentSchemas
.PARAMETER Description
A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation.
.PARAMETER Required
Determines if the request body is required in the request. Defaults to false.
.PARAMETER Properties
Use to force the use of the properties keyword under a schema. Commonly used to specify a multipart/form-data multi file
.PARAMETER Examples
Supplied an Example of the media type. The example object SHOULD be in the correct format as specified by the media type.
The `example` field is mutually exclusive of the `examples` field.
Furthermore, if referencing a `schema` which contains an example, the `example` value SHALL _override_ the example provided by the schema.
.PARAMETER Encoding
This parameter give you control over the serialization of parts of multipart request bodies.
This attribute is only applicable to multipart and application/x-www-form-urlencoded request bodies.
Use New-PodeOAEncodingObject to define the encode
.PARAMETER DefinitionTag
An Array of strings representing the unique tag for the API specification.
This tag helps distinguish between different versions or types of API specifications within the application.
You can use this tag to reference the specific API documentation, schema, or version that your function interacts with.
.EXAMPLE
New-PodeOARequestBody -Content @{ 'application/json' = (New-PodeOAIntProperty -Name 'userId' -Object) }
.EXAMPLE
New-PodeOARequestBody -Content @{ 'application/json' = 'UserIdSchema' }
.EXAMPLE
New-PodeOARequestBody -Reference 'UserIdBody'
.EXAMPLE
New-PodeOARequestBody -Content @{'multipart/form-data' =
New-PodeOAStringProperty -name 'id' -format 'uuid' |
New-PodeOAObjectProperty -name 'address' -NoProperties |
New-PodeOAObjectProperty -name 'historyMetadata' -Description 'metadata in XML format' -NoProperties |
New-PodeOAStringProperty -name 'profileImage' -Format Binary |
New-PodeOAObjectProperty
} -Encoding (
New-PodeOAEncodingObject -Name 'historyMetadata' -ContentType 'application/xml; charset=utf-8' |
New-PodeOAEncodingObject -Name 'profileImage' -ContentType 'image/png, image/jpeg' -Headers (
New-PodeOAIntProperty -name 'X-Rate-Limit-Limit' -Description 'The number of allowed requests in the current period' -Default 3 -Enum @(1,2,3)
)
)
#>
function New-PodeOARequestBody {
[CmdletBinding(DefaultParameterSetName = 'BuiltIn' )]
[OutputType([hashtable])]
[OutputType([System.Collections.Specialized.OrderedDictionary])]
param(
[Parameter(Mandatory = $true, ParameterSetName = 'Reference')]
[string]
$Reference,
[Parameter(Mandatory = $true, ParameterSetName = 'BuiltIn')]
[Alias('ContentSchemas')]
[hashtable]
$Content,
[Parameter(ParameterSetName = 'BuiltIn')]
[string]
$Description,
[Parameter(ParameterSetName = 'BuiltIn')]
[switch]
$Required,
[Parameter(ParameterSetName = 'BuiltIn')]
[switch]
$Properties,
[System.Collections.Specialized.OrderedDictionary]
$Examples,
[hashtable[]]
$Encoding,
[string[]]
$DefinitionTag
)
$DefinitionTag = Test-PodeOADefinitionTag -Tag $DefinitionTag
$result = [ordered]@{}
foreach ($tag in $DefinitionTag) {
switch ($PSCmdlet.ParameterSetName.ToLowerInvariant()) {
'builtin' {
$param = [ordered]@{content = ConvertTo-PodeOAObjectSchema -DefinitionTag $tag -Content $Content -Properties:$Properties }
if ($Required.IsPresent) {
$param['required'] = $Required.IsPresent
}
if ( $Description) {
$param['description'] = $Description
}
if ($Examples) {
if ( $Examples.'*/*') {
$Examples['"*/*"'] = $Examples['*/*']
$Examples.Remove('*/*')
}
foreach ($k in $Examples.Keys ) {
if (!($param.content.Keys -contains $k)) {
$param.content[$k] = [ordered]@{}
}
$param.content[$k].examples = $Examples.$k
}
}
}
'reference' {
Test-PodeOAComponentInternal -Field requestBodies -DefinitionTag $tag -Name $Reference -PostValidation
$param = [ordered]@{
'$ref' = "#/components/requestBodies/$Reference"
}
}
}
if ($Encoding) {
if (([string]$Content.keys[0]) -match '(?i)^(multipart.*|application\/x-www-form-urlencoded)$' ) {
$r = [ordered]@{}
foreach ( $e in $Encoding) {
$key = [string]$e.Keys
$elems = [ordered]@{}
foreach ($v in $e[$key].Keys) {
if ($v -ieq 'headers') {
$elems.headers = ConvertTo-PodeOAHeaderProperty -Headers $e[$key].headers
}
else {
$elems.$v = $e[$key].$v
}
}
$r.$key = $elems
}
$param.Content.$($Content.keys[0]).encoding = $r
}
else {
# The encoding attribute only applies to multipart and application/x-www-form-urlencoded request bodies
throw ($PodeLocale.encodingAttributeOnlyAppliesToMultipartExceptionMessage)
}
}
$result[$tag] = $param
}
return $result
}
<#
.SYNOPSIS
Validate a parameter with a provided schema.
.DESCRIPTION
Validate the parameter of a method against it's own schema