【问题标题】:Graphql run a certain query from a set of multiple queries - ApolloClientGraphql 从一组多个查询中运行某个查询 - ApolloClient
【发布时间】:2017-03-07 12:56:47
【问题描述】:

我想将我的查询存储在一个外部文件中,比如说:

query GetAllTodos {
  todos{
    _id
    todoMessage
    createdAt
  }
}

query GetAllTests {
  tests
}

是否有可能以某种方式将整个文件加载到单个字符串中,将该字符串传递给 ApolloClient 并选择我要执行的查询,例如:

apollo.query({query: gql([allQueries])}, select: 'TodoQuery').then(({data})=>data);

是否可以与任何其他客户端一起执行此操作?不需要阿波罗。

【问题讨论】:

    标签: typescript graphql apollostack


    【解决方案1】:

    我不知道有什么方法可以专门使用现有工具来做到这一点。

    话虽如此,您可以从这些查询中创建一个模块(假设您使用的是 ES6+ 和包 graphql-tag):

    // queries.js
    export const GetAllTodos = gql`...`
    export const GetAllTests = gql`...`
    
    // Where you do a query
    import { GetAllTodos, GetAllTests } from './queries.js';
    apollo.query({ query: GetAllTodos }).then(( { data } => data);
    

    如果您需要更多动态性,queries.js 模块可以导出一个可以映射到这些的函数:

    // queries.js
    export const queries = {
      'GetAllTodos': gql`...`,
      'GetAllTests': gql`...`'
    };
    
    export default function selectQuery(key) {
      return queries[key];
    }
    
    // Where you do a query
    import selectQuery from './queries.js';
    apollo.query({ query: selectQuery('GetAllTodos') }).then(( { data } => data);
    

    然后,您可以对此进行扩展,尝试搜索与“TodoQuery”匹配的查询,但随后将查询命名为与原始示例中类似的其他名称。

    【讨论】:

      猜你喜欢
      • 2017-03-12
      • 2021-02-18
      • 2018-12-21
      • 2020-08-17
      • 2019-07-11
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      相关资源
      最近更新 更多