Created
December 2, 2023 20:45
-
-
Save jkone27/a88c209794bbf7e7064c74a0200beab6 to your computer and use it in GitHub Desktop.
Add and retrieve some pets using F# awesome SwaggerProvider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#r "nuget: SwaggerProvider" | |
#r "nuget: Microsoft.Extensions.Logging.Console" | |
#r "nuget: Microsoft.Extensions.DependencyInjection" | |
#r "nuget: Microsoft.Extensions.Http" | |
open System | |
open System.Net.Http | |
open SwaggerProvider | |
open System.Threading.Tasks | |
open System.Threading | |
open Microsoft.Extensions.DependencyInjection | |
open Microsoft.Extensions.Logging | |
open Microsoft.Extensions.Http | |
open System.Net.Http | |
let [<Literal>] Schema = "https://petstore.swagger.io/v2/swagger.json" | |
type PetStore = OpenApiClientProvider<Schema> | |
// fast version of configure services to get DI and logging! | |
let configureServices () = | |
let services = new ServiceCollection() | |
services.AddHttpClient() | |
services.AddLogging(fun l -> l.AddConsole() |> ignore) | |
services | |
// get you service provider for DI container | |
let sp = configureServices().BuildServiceProvider() | |
// add pet method, given an id and pet name | |
let ``add your pet`` id petName = | |
task { | |
// `BaseAddress` uri should ends with '/' because TP generate relative uri | |
let httpClient = sp.GetRequiredService<HttpClient>() | |
httpClient.BaseAddress <- new Uri("https://petstore.swagger.io/v2/") | |
let client = new PetStore.Client(httpClient) | |
let pet = new PetStore.Pet(Id = Some(id), Name = petName) | |
do! client.AddPet(pet) | |
return id, petName | |
} | |
// get pet given id | |
let ``get your pet`` id = | |
task { | |
// `BaseAddress` uri should ends with '/' because TP generate relative uri | |
let httpClient = sp.GetRequiredService<HttpClient>() | |
httpClient.BaseAddress <- new Uri("https://petstore.swagger.io/v2/") | |
let client = new PetStore.Client(httpClient) | |
// Request data back and deserialize to provided type | |
let! myPet = client.GetPetById(id) | |
return myPet | |
} | |
// RUN and select CODE below | |
// add as many pets as you like | |
[ | |
1001L, "jhonny" | |
1002L, "fido" | |
1003L, "bravo" | |
1004L, "happy" | |
1005L, "miao" | |
1006L, "bao" | |
] | |
|> Seq.map (fun (id,name) -> ``add your pet`` id name) | |
|> Task.WhenAll // parallel add | |
|> Async.AwaitTask | |
|> Async.RunSynchronously | |
|> Seq.map (fun (id,_) -> ``get your pet`` id) | |
|> Task.WhenAll // parallel get | |
|> Async.AwaitTask | |
|> Async.RunSynchronously // print results | |
|> Seq.iter (fun p -> printfn $"Added and retrieved your new pet: {p.Category} with name {p.Name}, cool!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment