moi
Published on

Facilitate Fetch API Calls

Authors
  • avatar
    Name
    Mathieu Sévégny
    Twitter

Facilitate Fetch API Calls

1. Put your base API URL in a constant

/**
 * Base URL for the API
 */
export const API_BASE_URL = "HERE ADD YOUR API URL";

2. Create a type and interface to facilitate the use of the function

/**
 * HTTP Methods.
 */
type Method = "GET" | "POST" | "PATCH" | "PUT" | "DELETE"

/**
 * Result of API call.
 */
interface APIResult<T>{
    data?:T;
    error?:string;
}

3. Create a function to generate options for fetch

/**
 * Create options for the fetch request.
 * @param method HTTP method.
 * @param isAuth Is user connected?
 * @param data Data to send.(If needed)
 * @returns « Init » needed to make the fetch request.
 * @example
 * await fetch(url+ "/login",createRequestOptions("POST",false,body))
         .then(async (response) => {
                user = JSON.parse(await response.text());
              })
 */
export function createRequestOptions(method:Method,isAuth:boolean,data?:any){
    //Create headers for the request.
    let header = new Headers();
    //Specify the content type in the header.
    header.append("Content-Type","application/json")

    let init : any = {method:method};

    if (isAuth) {
        //Get the token with a function.
        //Adds the token to the header.
        header.append("Authorization",`Bearer ${getToken()}`)
    }

    //Add the header to the init.
    init.headers = header;

    if (data !== null){
        //Add the data to the init.
        init.body = JSON.stringify(data);
    }

    return init;
}

4. Create a function to make an API call

/**
 * Do an API request.
 * @param endURL End of URL.
 * @param method HTTP method.
 * @param isAuth Is user connected?
 * @param body Data to send.(If needed)
 * @returns Response of the API call.
 */
export async function APIRequest<T>(endURL:string,method:Method,isAuth:boolean,body?:any):Promise<APIResult<T>>{
    let data;
    let error;
    try{
        await fetch(API_BASE_URL+endURL,createRequestOptions(method,isAuth,body))
        .then(response => {
            return response.text();
        })
        .then(text => {
            data = JSON.parse(text);
            //In my API if there is an error, the reveived data as no content.
            if (!data.content){
                error = data.message;
            }
            else{
                data = data.content;
            }
        })
    }
    catch(e){
        error = "The connection to the server failed.";
    }

    return {data,error}
}

5. Now you can make an API call like this

const body = {
    email,
    password
}
const response : APIResult<string> = await APIRequest("token","POST",false,body);

if (response.error){
    //Error
}
else{
    //Success
}