gpt4 book ai didi

javascript - 如何优化 API 获取以减少冗余

转载 作者:行者123 更新时间:2023-11-29 10:26:05 25 4
gpt4 key购买 nike

我正在构建一个使用 API 的 React 应用程序,我现在构建的是 2 个函数,它们都获取相同的 URL,但更改 API 端点的第二部分,如 URL/?searchURL/?i=123 但我想实现的是减少冗余代码,所以我想制作一个只采用相同 URL 并根据 URL 的第二部分更改的函数在通话中。

顺便说一句,这种方法给我带来了问题。

我原来做的代码是这样的:

import {API_MOVIE_URL, API_KEY} from "./ApisConst";

export const getMoviesBySearch = async search => {
try {
const url = `${API_MOVIE_URL}?apikey=${API_KEY}&${search}`;
const response = await fetch(url);
const json = await response.json();
return json;
} catch {
return {
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
};
}
};

export const getMoviesInfo = async movieID => {
try {
const url = `${API_MOVIE_URL}?apikey=${API_KEY}&i=${movieID}&plot`;
const response = await fetch(url);
const json = await response.json();
return json;
} catch {
return {
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
};
}
};

我尝试的改变是:

const fetchAPI = async ({type, query}) => {
const queryParams = {
byString: `&${query}`,
byMovieId: `&i=${query}&plot`,
};

const endpoint = `${API_MOVIE_URL}?apikey=${API_KEY}${queryParams[type]}`;
console.log("fetching", endpoint);

return fetch(endpoint)
.then(res => res)
.catch(() => ({
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
}));
};

export const getMoviesBySearch = async search =>
await fetchAPI({type: "byString", query: search});

export const getMoviesInfo = async movieID =>
await fetchAPI({type: "byMovieId", query: movieID});

但是第二种方法在控制台中给我一个错误:

Response {type: "cors", url: "https://www.omdbapi.com/?apikey=API_KEY&s=harry+potter&type=movie", redirected: true, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: true
status: 200
statusText: ""
type: "cors"
url: "https://www.omdbapi.com/?apikey=API_KEY&s=harry+potter&type=movie"

第一种方法非常有效,但第二种方法无效,并且试图获得解决方案但无法真正考虑如何更好地优化此代码。

最佳答案

由于除了 url 之外查询是相同的,因此创建一个查询生成器 (createMoviesQuery),它接受一个生成 url (urlGenerator) 的函数,并返回一个查询功能

示例(未测试):

import {API_MOVIE_URL, API_KEY} from "./ApisConst";

const createMoviesQuery = urlGenerator => async (...params) => {
try {
const url = urlGenerator(...params);
const response = await fetch(url);
const json = await response.json();
return json;
} catch {
return {
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
};
}
};

export const getMoviesBySearch = createMoviesQuery((search) => `${API_MOVIE_URL}?apikey=${API_KEY}&${search}`);

export const getMoviesInfo = createMoviesQuery((movieID) => `${API_MOVIE_URL}?apikey=${API_KEY}&i=${movieID}&plot`);

关于javascript - 如何优化 API 获取以减少冗余,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59060644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com