Files
puregym-unofficial-dotnet/PureGym/Api.fs
patrick 419f27053f
All checks were successful
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/push/all-checks-complete Pipeline was successful
Add all-gyms (#11)
Co-authored-by: Smaug123 <patrick+github@patrickstevens.co.uk>
Reviewed-on: #11
2024-02-12 22:08:02 +00:00

46 lines
1.6 KiB
Forth

namespace PureGym
open System
open System.Net.Http
open System.Threading
open System.Threading.Tasks
/// Methods for interacting with the PureGym REST API.
[<RequireQualifiedAccess>]
module Api =
/// Create a REST client, authenticated as the specified user. Creds will be refreshed if possible as long as
/// the returned disposable is not disposed.
let make (auth : Auth) : (IPureGymApi * IDisposable) Task =
let cache, getToken =
match auth with
| Auth.Token t ->
{ new IDisposable with
member _.Dispose () = ()
},
fun () -> t
| Auth.User cred ->
let cache = new Cache<_> (AuthToken.get cred, _.ExpiryTime)
cache :> _, (fun () -> Async.RunSynchronously (cache.GetCurrentValue ()))
async {
let client = new HttpClient ()
return PureGymApi.make (getToken >> _.AccessToken >> sprintf "Bearer %s") client, cache
}
|> Async.StartAsTask
/// Create a REST client, authenticated as the specified user. Do not refresh creds.
let makeWithoutRefresh (ct : CancellationToken) (auth : Auth) : IPureGymApi Task =
async {
let! token =
match auth with
| Auth.Token t -> async.Return t
| Auth.User cred -> Async.AwaitTask (AuthToken.get cred ct)
let client = new HttpClient ()
return PureGymApi.make (fun () -> $"Bearer %s{token.AccessToken}") client
}
|> Async.StartAsTask