我无法在typeDefs中导入schema.graphql文件:无法找到以下指针的任何GraphQL类型定义:

时间:2020-07-15 13:32:20

标签: node.js express graphql apollo-server

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

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

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

Error Image

这是我的代码:

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

但这根本不起作用

1 个答案:

答案 0 :(得分:0)

对我来说很好。软件包版本:

"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"}}