Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
usamnet000 opened this issue May 18, 2020 · 1 comment

Comments

@usamnet000
Copy link

usamnet000 commented May 18, 2020

لماذا لا يكون استدعى 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 usamnet000 changed the title تحسين fetch يستدعى عند الحاجة وللتنضيم تحسين fetch الإستدعاء عند الحاجة للتنضيم والاداء May 18, 2020
@usamnet000 usamnet000 changed the title تحسين fetch الإستدعاء عند الحاجة للتنضيم والاداء مقترح: تحسين fetch الإستدعاء عند الحاجة للتنضيم والاداء May 18, 2020
@usamnet000 usamnet000 changed the title مقترح: تحسين fetch الإستدعاء عند الحاجة للتنضيم والاداء تحسين fetch الإستدعاء عند الحاجة للتنضيم والاداء May 18, 2020
@usamnet000
Copy link
Author

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);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant