|
| 1 | +namespace Web.Sample |
| 2 | + |
| 3 | +#nowarn 20 // to avoid |> ignore everywhere in aspnet config files |
| 4 | + |
| 5 | +open System |
| 6 | +open Microsoft.AspNetCore.Builder |
| 7 | +open Microsoft.Extensions.Hosting |
| 8 | +open Microsoft.Extensions.DependencyInjection |
| 9 | +open System.Threading.Tasks |
| 10 | +open Microsoft.AspNetCore.Http |
| 11 | + |
| 12 | +module Clients = |
| 13 | + open System.Net.Http |
| 14 | + open System.Net.Http.Json |
| 15 | + |
| 16 | + module Routes = |
| 17 | + let name = "/hello/name" |
| 18 | + let age = "/hello/age" |
| 19 | + |
| 20 | + let ``localhost:5000`` (httpClient: HttpClient) = |
| 21 | + httpClient.BaseAddress <- "http://localhost" |> Uri |
| 22 | + |
| 23 | + type ClientOne(httpClient: HttpClient) = |
| 24 | + member this.GetNameAsync() = |
| 25 | + httpClient.GetFromJsonAsync<{| Name: string |}>(Routes.name) |
| 26 | + |
| 27 | + type ClientTwo(httpClient: HttpClient) = |
| 28 | + member this.GetAgeAsync() = |
| 29 | + httpClient.GetFromJsonAsync<{| Age: int |}>(Routes.age) |
| 30 | + |
| 31 | + |
| 32 | +module Services = |
| 33 | + open Clients |
| 34 | + |
| 35 | + let routeOne = "/service-one" |
| 36 | + |
| 37 | + type ServiceOne(clientOne: ClientOne, clientTwo: ClientTwo) = |
| 38 | + member this.GetAndPrintAsync() = |
| 39 | + task { |
| 40 | + let! name = clientOne.GetNameAsync() |
| 41 | + let! age = clientTwo.GetAgeAsync() |
| 42 | + |
| 43 | + return $"name: {name}, age:{age}" |
| 44 | + } |
| 45 | + |
| 46 | +// IMPORTANT: needed for WebApplicationFactory<T> |
| 47 | +type Program() = class end |
| 48 | + |
| 49 | +// entry point is allowed only in let function bindings, so we need to also have this |
| 50 | +module Program = |
| 51 | + |
| 52 | + [<EntryPoint>] |
| 53 | + let main args = |
| 54 | + |
| 55 | + let builder = |
| 56 | + WebApplication.CreateBuilder(args) |
| 57 | + |> fun x -> |
| 58 | + x.Services.AddHttpClient<Clients.ClientOne>(Clients.``localhost:5000``) |
| 59 | + x.Services.AddHttpClient<Clients.ClientTwo>(Clients.``localhost:5000``) |
| 60 | + x.Services.AddTransient<Services.ServiceOne>() |
| 61 | + x |
| 62 | + |
| 63 | + let app = builder.Build() |
| 64 | + |
| 65 | + // our app service is invoked in this route |
| 66 | + app.MapPost(Services.routeOne, Func<HttpContext, _>(fun c -> |
| 67 | + task { |
| 68 | + let s = c.RequestServices.GetRequiredService<Services.ServiceOne>() |
| 69 | + |
| 70 | + let! r = s.GetAndPrintAsync() |
| 71 | + |
| 72 | + return r |
| 73 | + }) |
| 74 | + ) |
| 75 | + |
| 76 | + // test api client against these endpoints to avoid extra server hosting in app / containers etc |
| 77 | + app.MapGet("/hello/name", Func<{| Name: string |}>(fun () -> {| Name = "john" |})) |
| 78 | + app.MapGet("/hello/age", Func<{| Age: int |}>(fun () -> {| Age = 25 |})) |
| 79 | + |
| 80 | + app.Run() |
| 81 | + |
| 82 | + 0 // Exit code |
| 83 | + |
0 commit comments