如何优化具有相同功能的 APIs header

How to optimize APIs function with the same header

我正在使用 fetch 来处理 API,我必须将 header 添加到每个 API 函数中,如下所示。重复的太多了。

getSomething: async() => {
    const user: IUserData = await JSON.parse(localStorage.getItem("token")!),
      userCompanies: ICompanies = await JSON.parse(localStorage.getItem("companies")!),
      companyId = Object.keys(userCompanies.Company)[0], meId = user.userInfo.data.id, myHeaders = new Headers();
    myHeaders.append("authorization", user.accessToken.token);
    myHeaders.append("company-id", companyId);

    const requestOptions: RequestInit = {
      headers: myHeaders,
      method: "GET",
      redirect: "follow"
    };

    return fetch(url + `/${meId}/calendars?type=tree`, requestOptions)
      .then((response) => response.json())
      .then((result) => result)
      .catch((error) => error);
  }

如何减少或优化它们?

我想你可以做到这一点的方法是将它分组到一个存储中class,你会发现它在访问数据时很有用

//Setter
localStorage.setItem('myHeaders', data);
// getter
localStorage.getItem('myHeaders');

要使用本地存储,请查看这篇文章 https://medium.com/@siobhanpmahoney/local-storage-in-a-react-single-page-application-34ba30fc977d

尝试通过创建自己的 GET 方法来抽象 fetch,例如

async function get(url: string, options?: RequestInit) {
    const user: IUserData = await JSON.parse(localStorage.getItem("token")!);
    const userCompanies: ICompanies = await JSON.parse(localStorage.getItem("companies")!);
    const companyId = Object.keys(userCompanies.Company)[0];
    const meId = user.userInfo.data.id;
    
    const myHeaders = new Headers();
    myHeaders.append("authorization", user.accessToken.token);
    myHeaders.append("company-id", companyId);
    
  const baseOptions: RequestInit = {
    headers: myHeaders,
    method: "GET",
    redirect: "follow"
  };

  // merge passed options with your baseOptions

  let baseUrl = 'your-base-url';
  return fetch(baseUrl + `/${meId}/${url}`, baseOptions)
    .then((response) => response.json())
    .then((result) => result)
    .catch((error) => error);
}

getSomething: async() => {
  return get('/calendars?type=tree')
}

这只是一个想法,因为我不确定哪些参数可以在许多不同的请求中重复使用。您甚至可能最终得到 baseGet,它只处理所有请求共享的核心功能,然后得到 baseCompanyGet,它是 baseGet 的抽象,仅供公司请求等使用。

我们的想法是识别重复的代码并将其放入某种基本方法中,而您仅通过方法参数传递动态数据。