Reseal fetch for RESTful

Because the RESTful API is used in the background and Token is used for authentication, it is better to encapsulate the fetch one more layer

First define several constants

  1. Since there are two types of API requests: form and JSON, define the constant of ContentType first
  2. The RESTful API generally uses five methods: GET/POST/PUT/PATCH/DELETE, which are also defined as constants of HttpMethod
export const ContentType = {
    JSON : "application/json;charset=UTF-8",
    FORM : "application/x-www-form-urlencoded; charset=UTF-8"
};

export const HttpMethod = {
    GET : "GET",
    POST : "POST",
    PUT : "PUT",
    PATCH : "PATCH",
    DELETE : "DELETE"
};

Define the Header's get function

Because Token authentication is used, a getHeaders function is written to get the Token from the Cookie.

const getHeaders = () => {
    const token = Cookies.get(COOKIE_TOKEN);
    return {
        "Content-Type": ContentType.JSON,
        "Token": token
    }
};

Encapsulation request method

Here we take GET and POST as examples, and then we only need to pay attention to the URL and body of the request to call the method.

export const _get = (url,body = null) => {
    if(body !== null){
        url = new URL(url);
        Object.keys(body).forEach(key => url.searchParams.append(key, body[key]));
    }

    const promise = fetch(url,{
        method : HttpMethod.GET,
        headers: getHeaders(),
    });
    return handleFetch(promise);
};

export const _post = (url,body) => {
    const promise = fetch(url,{
        method : HttpMethod.POST,
        headers: getHeaders(),
        body : JSON.stringify(body)
    });
    return handleFetch(promise);
};

Two auxiliary functions

  1. checkStatus is used to check whether the Response status is 200. If it is 200, it will be converted to an object. If it is not 200, an exception will be thrown to other places for processing
  2. handleFetch is used to catch exceptions and call realop to notify of request errors
export const checkStatus = response => {
    if(response.status === 200){
        return response.json();
    }
    else {
        throw new Error();
    }
};

const handleFetch = promise => {
    return promise
        .then(response => checkStatus(response))
        .catch(() => dispatch(error(FAIL_RESULT.message)))
};

Tags: JSON

Posted on Tue, 31 Mar 2020 10:12:32 -0700 by taquitosensei