在Apollo应用中,GraphQL查询可能会触发数百个重复请求的问题可以通过以下步骤解决:
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
cache: new InMemoryCache(),
});
import { ApolloLink } from '@apollo/client';
const dedupLink = new ApolloLink((operation, forward) => {
// 检查是否已经发起相同参数的请求
const { operationName, variables } = operation;
const existingOperation = findExistingOperation(operationName, variables);
if (existingOperation) {
// 返回已存在的操作的结果,而不发起新请求
return existingOperation;
}
// 将新操作添加到已存在操作列表中
addOperationToExistingOperations(operationName, variables, forward);
// 发起新请求
return forward(operation);
});
const client = new ApolloClient({
link: dedupLink.concat(/* 其他Link */),
cache: new InMemoryCache(),
});
import { RESTDataSource } from 'apollo-datasource-rest';
class MyDataSource extends RESTDataSource {
async getData() {
const cachedData = await this.get('cachedData');
if (cachedData) {
return cachedData;
} else {
const newData = await this.get('newData');
this.set('cachedData', newData); // 将数据存储在缓存中
return newData;
}
}
}
const server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => ({
myDataSource: new MyDataSource(),
}),
});
通过使用以上方法,你可以有效地解决Apollo应用中GraphQL查询触发数百个重复请求的问题,并提高应用的性能和效率。