我无法在 typeDefs 中导入 schema.graphql 文件:找不到以下指针的任何 GraphQL 类型定义:
Posted
技术标签:
【中文标题】我无法在 typeDefs 中导入 schema.graphql 文件:找不到以下指针的任何 GraphQL 类型定义:【英文标题】:I'm unable to import schema.graphql file in typeDefs : Unable to find any GraphQL type definitions for the following pointers: 【发布时间】: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 ;
不仅如此,我也尝试过这个解决方案 - *** Solution
但这根本不起作用
【问题讨论】:
【参考方案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"
【讨论】:
以上是关于我无法在 typeDefs 中导入 schema.graphql 文件:找不到以下指针的任何 GraphQL 类型定义:的主要内容,如果未能解决你的问题,请参考以下文章