Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

javascript - 如何使Javascript中的提取API模块化(How to make a fetch API in Javascript to be modular)

I'm building an APP in React where I would like to consume an API for comments which allows crud rules.(我正在React中构建一个APP,我想使用一个API进行注释,以允许使用杂乱的规则。)

What I'm trying to build is a modular fetch that is implemented once and all the CRUD rules use the same fetch in one place where the base URL of the API is defined.(我要构建的是一次实现的模块化提取,并且所有CRUD规则都在定义API基本URL的一个地方使用相同的提取。) Via the CRUD functionalities, I will just pass the endpoint I need and the related params and method.(通过CRUD功能,我将仅传递所需的端点以及相关的参数和方法。) That will make life easier to use it around the APP when need it.(这将使生活更容易在需要时在APP周围使用。)

What I built first was my BaseAPI functionality as follow:(我首先构建的是BaseAPI功能,如下所示:)

import { COMMENT_USER, COMMENT_PASS } from "./ConstAPI";

export const createCommentAPIQUery = urlGenerator => async (...params) => {
  try {
    const url = urlGenerator(...params);
    const token = btoa(COMMENT_USER + ":" + COMMENT_PASS);
    const credentials = {
      method: "GET",
      headers: new Headers({
        Authorization: "Basic " + token,
        "Content-Type": "application/json",
        Accept: "application/json"
      })
    };
    const response = await fetch(url, credentials);
    const json = response.json();
    return {
      success: true,
      ...json
    };
  } catch {
    return {
      success: false,
      result: [],
      message:
        "There is an issue to get data from server. Please try again later."
    };
  }
};

The issue above is that that will work when I use the GET but for the other CRUD will not as I need to pass a method and in case of a POST and PUT also stringify().(上面的问题是,当我使用GET时,它将起作用,但对于其他CRUD,将不起作用,因为我需要传递一个方法,并且在POST和PUT的情况下,还需要stringify()。)

So the following CRUD functionalities were my attempt but as you will see that works only for the GET method and I need to find a solution for the rest of the methods:(因此,下面的CRUD功能是我的尝试,但是如您所见,它仅对GET方法有效,我需要为其余方法找到一种解决方案:)
import { createCommentAPIQUery } from "./BaseCommentAPI";
import { COMMENT_URL } from "./ConstAPI";

export const getAllComments = createCommentAPIQUery(
  asin => `${COMMENT_URL}/comments/${asin}`
);

export const addComment = createCommentAPIQUery(body => {
  `${COMMENT_URL}/comments`, (this.credentials.method = "POST");
  this.credentials.body = JSON.stringify(body);
});

export const updateComment = createCommentAPIQUery((id, body) => {
  `${COMMENT_URL}/comments/${id}`, (this.credentials.method = "PUT");
  this.credentials.body = JSON.stringify(body);
});

export const deleteComment = createCommentAPIQUery(id => {
  `${COMMENT_URL}/comments/${id}`, (this.credentials.method = "DELETE");
});

What I need is a good idea to make that work as I thought about it but actually I stack in it.(我需要的是一个很好的主意,以使它按我的想法进行工作,但实际上我将其堆叠。)

As it is now is generating an error as:(由于它现在正在生成错误,如下所示:)

Expected an assignment or function call and instead saw an expression  no-unused-expressions

So I need to figure out a good way to complete this idea and to avoid issues and bugs.(因此,我需要找到一种很好的方法来完成此想法,并避免出现问题和错误。)

  ask by Jakub translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Pass your body and method as arguments not part of your url generator code, method with the outer function and body with the inner(通过你的bodymethod作为参数不是你的URL生成代码的一部分, method与外部功能和body与内)

export const createCommentAPIQUery = (urlGenerator,method='GET') => async (body,...params) => {
  try {
    const url = urlGenerator(...params);
    const token = btoa(COMMENT_USER + ":" + COMMENT_PASS);
    const credentials = {
      //use passed method and body accordingly
      method: method,
      body:body,
      headers: new Headers({
        Authorization: "Basic " + token,
        "Content-Type": "application/json",
        Accept: "application/json"
      })
    };

Example use:(使用示例:)

export const getAllComments = createCommentAPIQUery((asin)=>{ 
  return `${COMMENT_URL}/comments/${asin}`; 
});
//calling, pass null as no body is needed, and 'theAsin' will become part of 'params'
getAllComments(null,theAsin).then(...);

export const addComment = createCommentAPIQUery(()=>{ 
  return `${COMMENT_URL}/comments`; 
},"POST");
//calling, pass in body, and no other arguments are needed for 'params'
addComment(JSON.stringify(body)).then(...);

export const updateComment = createCommentAPIQUery((id)=>{ 
  return `${COMMENT_URL}/comments/${id}`; 
},"PUT");
//calling, pass in body, and 'theId' will end up as part of 'params'
updateComments(JSON.stringify(body),theId);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...