【问题标题】:I'm unable to import schema.graphql file in typeDefs : Unable to find any GraphQL type definitions for the following pointers:我无法在 typeDefs 中导入 schema.graphql 文件:找不到以下指针的任何 GraphQL 类型定义:
【发布时间】:2020-11-05 00:33:10
【问题描述】:

我正在使用 apollo-server-express 通过 GraphQL 创建后端 api

现在,我想在单独的文件中编写 GraphQL Schema。例如“schema.graphql”,所以当我把之前在模板字符串中写的代码放在一起的时候。进入“schema.graphql”我的应用程序因以下错误而崩溃:

找不到以下指针的任何 GraphQL 类型定义

这是我的代码:

server.js

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const { importSchema } = require('graphql-import');
const fs = require('fs');
const path = '/graphql';


const apolloServer = new ApolloServer({
  typeDefs: importSchema('./greet.graphql'),
  resolvers: require('./graphql/resolver'),
});

const app = express();
apolloServer.applyMiddleware({ app, path });

app.listen(8080, () => {
  console.log('Server Hosted');
}); 

greet.graphql

type Query {
  greeting: String
}

resolver.js

const Query = {
  greeting: () => 'Hello World From NightDevs',
};

module.exports = { Query };

不仅如此,我也尝试过这个解决方案 - Stackoverflow Solution

但这根本不起作用

【问题讨论】:

    标签: node.js express graphql apollo-server


    【解决方案1】:

    对我来说很好用。包版本:

    "apollo-server-express": "^2.12.0",
    "graphql-import": "^0.7.1",
    

    例子:

    server.js:

    const express = require('express');
    const { ApolloServer } = require('apollo-server-express');
    const { importSchema } = require('graphql-import');
    const path = require('path');
    
    const apolloServer = new ApolloServer({
      typeDefs: importSchema(path.resolve(__dirname, './greet.graphql')),
      resolvers: require('./resolver')
    });
    
    const app = express();
    const graphqlEndpoint = '/graphql';
    apolloServer.applyMiddleware({ app, path: graphqlEndpoint });
    
    app.listen(8080, () => {
      console.log('Server Hosted');
    });
    

    greet.graphql:

    type Query {
      greeting: String
    }
    

    resolver.js:

    const Query = {
      greeting: () => 'Hello World From NightDevs',
    };
    
    module.exports = { Query };
    

    通过curl进行测试:

    curl 'http://localhost:8080/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: http://localhost:8080' --data-binary '{"query":"query {\n  greeting\n}"}' --compressed
    

    得到结果:

    {"data":{"greeting":"Hello World From NightDevs"}}
    

    【讨论】:

      猜你喜欢
      • 2020-03-13
      • 2019-06-28
      • 2020-11-16
      • 2022-07-08
      • 2020-08-27
      • 2013-03-08
      • 2019-04-22
      • 1970-01-01
      • 2021-01-04
      相关资源
      最近更新 更多