GraphQLJS使用.graphql文件进行来自nodejs的查询

问题描述

我已经创建了一个基本的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

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

感谢您的帮助!

解决方法

您可以使用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' } ] }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...