我正在使用访存来处理API,我必须将标头添加到每个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);
}
如何减少或优化它们?
尝试fetch
通过制作自己的GET
方法进行抽象,例如
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
并且仅由公司请求使用,等等。
这个想法是识别要重复的代码并将其放入某种基本方法中,而您仅通过方法参数传递动态数据。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句