deimos-lang/sketching/curl.dms
2025-01-14 13:55:16 -06:00

75 lines
1.9 KiB
Plaintext

use std::http::jsonClient
fn main = jsonClient() # json client
post 'http://localhost:1234/login', username: 'test', password: 'test' # Either<Err, Response>
-> || ( it.body.accessToken ) # Either<Error, *>
|> println # IO
()
# Without operators
fn main = jsonClient()
post 'http://localhost:1234/login', username: 'test', password: 'test'
map || ( it.body.accessToken )
fold println
()
# Better: main which returns IO (a Callable?) automatically calls the IO
# Also, JsonClient can "login" using various methods, such as a Bearer token
use std::http::{jsonClient, bearerToken}
fn main = jsonClient(
baseUrl: 'http:/localhost:1234',
auth: bearerToken || ( post('/login', username: 'test', password: 'test') map || ( it.body.accessToken ) )
)
get '/greeting'
map || ( it.body.greeting )
fold println
pub int HttpReqOpts {
headers: Map<String, Any>
}
pub int GetOpts : HttpReqOpts
pub int HttpClient {
baseUrl: String
fn get(path: String, opts?: GetOpts): IOEither<HttpRequestError, HttpResponse>
fn post(path: String, body: Any, opts: PostOpts): IOEither<HttpRequestError, HttpResponse>
}
pub int JsonClient : HttpClient
pub int JsonClientOpts {
baseUrl: String
auth: HttpClientAuth
}
pub int HttpClientAuth = (reqBuilder: HttpRequest::Builder) -> Void
impl : JsonClient {
baseUrl: String
fld auth: HttpClientAuth
ctor (opts: JsonClientOpts) {
self.{baseUrl, auth} = opts
}
impl fn get(path, opts) = IOEither::of || (
HttpRequest::builder() tap || {
url = baseUrl + path
method = 'GET'
headers = opts?.headers ?: [:]
cookies = opts?.cookies ?: [:]
auth(self)
}()
)
}
pub fn jsonClient(opts: JsonClientOpts): JsonClient = JsonClientImpl(opts)
pub fn bearerToken(tokenGetter: (#[self] client: JsonClient) -> IOEither<HttpRequestError, String>): HttpClientAuth {
// todo
}