Skip to content

Commit

Permalink
refactor: fetch api changes (#763)
Browse files Browse the repository at this point in the history
  • Loading branch information
PritishBudhiraja authored Nov 4, 2024
1 parent f1e63f1 commit be0146f
Showing 1 changed file with 51 additions and 29 deletions.
80 changes: 51 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,56 @@ 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),
},
)

//* Fetch.Response.ok - Response status code - 200-299
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

0 comments on commit be0146f

Please sign in to comment.