Skip to content

Commit

Permalink
wip on response
Browse files Browse the repository at this point in the history
  • Loading branch information
dmmulroy committed Mar 13, 2024
1 parent e14d465 commit 73f990a
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 14 deletions.
22 changes: 18 additions & 4 deletions src/glitch/api/client.gleam
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import gleam/list
import gleam/pair
import gleam/option.{type Option, None, Some}
import gleam/result
import gleam/uri
import gleam/http.{type Header, type Method, Get, Https}
import gleam/http/request.{type Request as HttpRequest, Request as HttpRequest}
import gleam/http/response.{type Response}
import gleam/httpc
import gleam/json.{type Json}
import glitch/extended/json_ext.{type JsonDecoder}
import glitch/extended/request_ext

const host = "api.twitch.tv/helix"
Expand Down Expand Up @@ -99,8 +102,19 @@ fn to_http_request(
|> request.set_query(query)
}

pub fn get(client: Client, request: Request) {
client
|> to_http_request(Get, request)
|> httpc.send
pub fn get(
client: Client,
request: Request,
decoder: JsonDecoder(String, output),
) -> Result(Response(output), ApiError) {
use response <- result.try(
client
|> to_http_request(Get, request)
|> httpc.send
|> result.replace_error(RequestError),
)

response
|> response.try_map(decoder)
|> result.replace_error(RequestError)
}
22 changes: 13 additions & 9 deletions src/glitch/api/user.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -102,19 +102,23 @@ pub fn query_params_from_get_users_request(

pub type GetUsersError {
DecodeError(DecodeError)
RequestError(Dynamic)
RequestError
}

// TODO: Deserialization is probably not working because the response is a list
pub fn get_users(
client: Client,
request: GetUsersRequest,
) -> Result(Response(String), GetUsersError) {
) -> Result(Response(User), GetUsersError) {
client
|> client.get(Request(
body: None,
headers: None,
path: "users",
query: query_params_from_get_users_request(request),
))
|> result.map_error(RequestError)
|> client.get(
Request(
body: None,
headers: None,
path: "users",
query: query_params_from_get_users_request(request),
),
of_json,
)
|> result.replace_error(RequestError)
}
5 changes: 4 additions & 1 deletion src/glitch/extended/json_ext.gleam
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import gleam/option.{type Option}
import gleam/uri.{type Uri}
import gleam/json.{type Json}
import gleam/json.{type DecodeError, type Json}

pub type JsonDecoder(input, output) =
fn(input) -> Result(output, DecodeError)

pub fn option(from opt: Option(a), using encoder: fn(a) -> Json) -> Json {
json.nullable(opt, encoder)
Expand Down

0 comments on commit 73f990a

Please sign in to comment.