request method
Makes the API request here
endPoint
- Endpoint of the API
method
- Type of APIMethod. Defaults to APIMethod.get See APIMethod enum for all the available methods
data
- data to be passed in the request in Map format
isAuthenticated
- if authenticated, Bearer token authorization will be added, otherwise not
Implementation
Future<Response> request(
String endPoint, {
APIMethod method = APIMethod.get,
Map? data,
bool isAuthenticated = true,
}) async {
/// Set url
final url = Uri.parse(baseUrl! + endPoint);
/// Create non-auth header
final headers = {'Content-Type': 'application/json'};
/// Add bearer token, if the API call is to be authenticated
if (isAuthenticated) {
String? token = await _getToken();
// TODO: add an assertion or check here, for null token
headers.addAll({'Authorization': 'Bearer $token}'});
}
late http.Response response;
/// switch on the basis of method provided and make relevant API call
switch (method) {
case APIMethod.get:
response = await client.get(url, headers: headers);
break;
case APIMethod.post:
response =
await client.post(url, headers: headers, body: json.encode(data));
break;
case APIMethod.put:
response =
await client.put(url, headers: headers, body: json.encode(data));
break;
case APIMethod.patch:
response =
await client.patch(url, headers: headers, body: json.encode(data));
break;
case APIMethod.delete:
response = await client.delete(url, headers: headers);
break;
}
return _handleResponse(response);
}