【问题标题】:GraphQLJS use a .graphql file for a query from nodejsGraphQL JS 使用 .graphql 文件从节点 js 进行查询
【发布时间】:2020-12-13 01:57:21
【问题描述】:

我已经创建了一个基本的 GraphQL Express 应用,我希望将来自预定义查询的预定义数据与特定路由捆绑在一起。

理想情况下,查询应该允许提供参数以便灵活使用,我希望能够将查询保存到文件并按需运行,但提供特定于当前所需数据的参数。

我可以用下面的查询来查询api

query authors(ids: [1337, 42]) {
  name,
  id
}

query.graphql 文件应如下所示:

getAuthorsById($ids: Int[]) {
  authors(ids: $ids) {
    name,
    id
  }
}

我想在 Node 服务器中做的是从 query.graphql 文件中获取内容,并在触发特定路由时执行它。

const query = somehowImportTheQuery('./query.graphql')
graphql(schema, query([1337, 42]))

上面的代码somehowImportTheQuery 应该导入查询并返回一个可以带参数调用的函数getAuthorsById

这样的东西已经存在了吗?或者是否有任何工具或文档可以帮助我实现所需的功能?

感谢您的帮助!

【问题讨论】:

    标签: node.js express graphql graphql-js


    【解决方案1】:

    您可以使用graphql-tools 模块中的documents-loading 从不同来源加载GraphQL 操作文档。

    例如

    index.ts:

    import { GraphQLSchema, buildSchema, graphql } from 'graphql';
    import { loadDocumentsSync, GraphQLFileLoader } from 'graphql-tools';
    import path from 'path';
    
    const typeDefs: string = `
        type Author {
            id: ID!
            name: String
        }
        type Query {
            authors(ids: [ID]!): [Author]!
        }
    `;
    const resolvers = {
      authors({ ids }) {
        return [
          { id: ids[0], name: 'a' },
          { id: ids[1], name: 'b' },
        ];
      },
    };
    
    const schema: GraphQLSchema = buildSchema(typeDefs);
    
    const query = loadDocumentsSync(path.resolve(__dirname, './query.graphql'), {
      loaders: [new GraphQLFileLoader()],
    });
    
    graphql({
      schema,
      source: query[0].rawSDL!,
      rootValue: resolvers,
      variableValues: { ids: [1337, 42] },
    }).then(({ data }) => {
      console.log(data);
    });
    

    query.graphql:

    query getAuthorsById($ids: [ID]!) {
      authors(ids: $ids) {
        name
        id
      }
    }
    

    执行结果:

    [Object: null prototype] {
      authors:
       [ [Object: null prototype] { name: 'a', id: '1337' },
         [Object: null prototype] { name: 'b', id: '42' } ] }
    

    【讨论】:

    • 感谢您的出色回答,非常完美。我已经做了一个基本的文件加载器,但最好像你建议的那样使用 graphql-tools。
    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 2019-12-28
    • 2018-05-31
    • 1970-01-01
    • 2020-02-06
    • 2017-08-10
    • 2016-12-03
    • 2021-10-31
    相关资源
    最近更新 更多