Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: fetch api changes #763

Merged
merged 10 commits into from
Nov 4, 2024
79 changes: 50 additions & 29 deletions src/Utilities/Utils.res
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,7 @@ let delay = timeOut => {
}, timeOut)->ignore
})
}

let getHeaders = (~uri=?, ~token=?, ~headers=Dict.make()) => {
let headerObj =
[
Expand All @@ -848,35 +849,6 @@ let getHeaders = (~uri=?, ~token=?, ~headers=Dict.make()) => {
})
Fetch.Headers.fromObject(headerObj->dictToObj)
}
let fetchApi = (uri, ~bodyStr: string="", ~headers=Dict.make(), ~method: Fetch.method) => {
open Promise
let body = switch method {
| #GET => resolve(None)
| _ => resolve(Some(Fetch.Body.string(bodyStr)))
}
body->then(body => {
Fetch.fetch(
uri,
{
method,
?body,
headers: getHeaders(~headers, ~uri),
},
)
->catch(err => {
reject(err)
})
->then(resp => {
resolve(resp)
})
})
}

let arrayJsonToCamelCase = arr => {
arr->Array.map(item => {
item->transformKeys(CamelCase)
})
}

let formatException = exc =>
switch exc {
Expand Down Expand Up @@ -904,6 +876,55 @@ let formatException = exc =>
| _ => exc->Identity.anyTypeToJson
}

let fetchApi = async (uri, ~bodyStr: string="", ~headers=Dict.make(), ~method: Fetch.method) => {
try {
let body = switch method {
| #GET => None
| _ => Some(Fetch.Body.string(bodyStr))
}

let response = await Fetch.fetch(
uri,
{
method,
?body,
headers: getHeaders(~headers, ~uri),
},
)

if !(response->Fetch.Response.ok) {
let errorText = await response->Fetch.Response.text
let status = response->Fetch.Response.status
let errorMessage = `FetchError: Failed to fetch (${status->Int.toString}): ${errorText}`
Error.raise(Error.make(errorMessage))
}

response
} catch {
| Exn.Error(error) => {
let errorMessage = switch Exn.message(error) {
| Some(msg) => msg
| None => "Unknown error occurred"
}

let enhancedError = Error.make(`APIError: ${errorMessage} (URL: ${uri})`)
Error.raise(enhancedError)
}
| err => {
let exceptionVal = err->formatException->getDictFromJson
let errorMessage = exceptionVal->getString("message", "Unknown error")
let errorType = exceptionVal->getString("type", "Unknown")
let networkError = Error.make(`${errorType}: ${errorMessage} (URL: ${uri})`)
Error.raise(networkError)
}
}
}
let arrayJsonToCamelCase = arr => {
arr->Array.map(item => {
item->transformKeys(CamelCase)
})
}

let getArrayValFromJsonDict = (dict, key, arrayKey) => {
dict
->Dict.get(key)
Expand Down
Loading