0

我们定义了一个带有两个 ApolloLinks 的 ApolloClient,与 MongoDB 和 PostgreSQL 连接,它运行良好:

const firstLink = new HttpLink({
  uri: 'graphql-postgre',
  //headers: yourHeadersHere,
  // other link options...
});
const secondLink = new HttpLink({
  uri: 'graphql-mongodb',
  //headers: yourHeadersHere
  // other link options...
});


const client = new ApolloClient({
 link: ApolloLink.split(
 o => o.getContext().clientName === "mongo", 
 secondLink, 
 firstLink // by default -> postgre)
 ),
 cache: new InMemoryCache(),
 fecthOptions: {
 mode: 'no-cors'
 },
 shouldBatch: true
});

现在,我们需要添加一个新链接才能访问新数据库(Neo4J),但我们找不到任何示例,也不知道是否可以使用两个以上的来源。我们尝试了以下代码,试图在第二个链接中包含一些逻辑,但它没有按我们预期的那样工作。我们从第一个和第二个链接获取信息,但不是从第三个链接获取信息:

const thirdLink = new HttpLink({
  uri: 'graphql-neo4j',
  //headers: yourHeadersHere
  // other link options...
});

const client = new ApolloClient({
  link: ApolloLink.split(
    o => o.getContext().clientName === "mongo", 
    secondLink, 
      (o => o.getContext().clientName === "neo", 
      thirdLink,
      firstLink) // by default -> postgre)
  ),
  cache: new InMemoryCache(),
  fecthOptions: {
    mode: 'no-cors'
  },
  shouldBatch: true
});

先感谢您。

4

1 回答 1

0

不幸的是 ApolloLink.split 只允许 2 个选项,但您仍然可以使用这种方法绕过该限制

const client = new ApolloClient({
link: ApolloLink.split(
(o) => o.getContext().clientName === 'mongo',
secondLink,
ApolloLink.split((o) => o.getContext().clientName === 'neo',
  thirdLink,
  firstLink)
), // by default -> postgre)
cache: new InMemoryCache(),
fecthOptions: {
mode: 'no-cors',
},
shouldBatch: true,
});
于 2022-02-21T16:16:24.283 回答