ramadan-2020-assessments icon indicating copy to clipboard operation
ramadan-2020-assessments copied to clipboard

تحسين fetch الإستدعاء عند الحاجة للتنضيم والاداء

Open usamnet000 opened this issue 4 years ago • 1 comments

لماذا لا يكون استدعى api في ملف منفصل وبدلا من التكرار يمكن كتابة دالة للمعالجة استدعاء api backend
يمكن انشاء طريقة لاستدعء الباك اند وإرسال البيانات والبيانات تسترجع الى callback

function backendLookup(method, endpoint, callback, data) {
  let jsonData;
  if (data) {
    jsonData = JSON.stringify(data);
  }
  const xhr = new XMLHttpRequest();

  const url = `http://localhost/api${endpoint}`; 
  xhr.responseType = "json";
  xhr.open(method, url);
  xhr.setRequestHeader("Content-Type", "application/json");

  xhr.onload = function () {
    if (xhr.status === 403) {
      const detail = xhr.response.detail;
      if (detail === "Authentication credentials were not provided.") {
        if (window.location.href.indexOf("login") === -1) {
          window.location.href = "/login?showLoginRequired=true";
        }
      }
    }
    callback(xhr.response, xhr.status);
  };
  xhr.onerror = function (e) {
    callback(
      {
        message: "The request was an error",
      },
      400
    );
  };
  xhr.send(jsonData);
}

لإستخدام الدالة بطريقة GET

function apiTweetList(username, callback, nextUrl) { //  nextUrl to paigation to load more List
    let endpoint = "/tweets/";
    if (username) { // filter list by username 
        endpoint = `/tweets/?username=${username}`;
    }
    backendLookup("GET", endpoint, callback);
}

const handleLoadListResponse = (response, status) => {
    if (status === 200) {} else {
        alert("There was an error");
    }
};
apiTweetList(username, handleLoadListResponse, nextUrl);

استدعى اخر للدالة بطريقة POST

function apiTweetCreate(newTweet, callback) {
    backendLookup("POST", "/tweets/create/", callback, {
        content: newTweet,
    });
}

const handleBackendUpdate = (response, status) => {
    if (status === 201) {
        didTweet(response)
    } else {
        console.log(response)
        alert("An error occured please try again")
    }
}

const newVal = textAreaRef.current.value
// backend api request
apiTweetCreate(newVal, handleBackendUpdate)
textAreaRef.current.value = ''

ايضا عن طريق هذة الدالة يمككن ارسال زر التصويب وعدم التصويب بإستخدام طريقة واحدة

function apiTweetAction(tweetId, action, callback) {
    const data = {
        id: tweetId,
        action: action,
    };
    backendLookup("POST", "/tweets/action/", callback, data);
}
const handleActionBackendEvent = (response, status) => {
    console.log(response, status);
    if ((status === 200 || status === 201)) {}
};
event.preventDefault();
apiTweetAction(tweet.id, action.type, handleActionBackendEvent); // action.type : "up" or "down"  

دائما انا افضل XMLHttpRequest على fetch لانها ابسط وأسرع في الاداء اتمنى لك التوفيق ونشكرا اخي على ما تقدمة من الاشياء المفيدة وربي يوفقك

usamnet000 avatar May 18 '20 03:05 usamnet000

csrftoken for post method:

function getCookie(name) {
  var cookieValue = null;
  if (document.cookie && document.cookie !== "") {
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
      var cookie = cookies[i].trim();
      // Does this cookie string begin with the name we want?
      if (cookie.substring(0, name.length + 1) === name + "=") {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}

export function backendLookup(method, endpoint, callback, data) {
  let jsonData;
  if (data) {
    jsonData = JSON.stringify(data);
  }
  const xhr = new XMLHttpRequest();

  const url = `api${endpoint}`;
  xhr.responseType = "json";
  const csrftoken = getCookie("csrftoken");
  xhr.open(method, url);
  xhr.setRequestHeader("Content-Type", "application/json");

  if (csrftoken) {
    // xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest")
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.setRequestHeader("X-CSRFToken", csrftoken);
  }

  xhr.onload = function () {
    if (xhr.status === 403) {
      const detail = xhr.response.detail;
      if (detail === "Authentication credentials were not provided.") {
        if (window.location.href.indexOf("login") === -1) {
          window.location.href = "/login?showLoginRequired=true";
        }
      }
    }
    callback(xhr.response, xhr.status);
  };
  xhr.onerror = function (e) {
    callback(
      {
        message: "The request was an error",
      },
      400
    );
  };
  xhr.send(jsonData);
}

usamnet000 avatar May 18 '20 04:05 usamnet000