如何使用apollo-server加载.graphql文件? [英] How to load a .graphql file using `apollo-server`?
问题描述
我当前正在使用单独的 .graphql
文件加载GraphQL模式,但该文件封装在字符串中:
I am currently loading the GraphQL schema using a separate .graphql
file, but it is encapsulated within strings:
schema.graphql
const schema = `
type CourseType {
_id: String!
name: String!
}
type Query {
courseType(_id: String): CourseType
courseTypes: [CourseType]!
}
`
module.exports = schema
然后将其用于 apollo服务器
:
index.js
const { ApolloServer, makeExecutableSchema } = require('apollo-server')
const typeDefs = require('./schema.graphql')
const resolvers = { ... }
const schema = makeExecutableSchema({
typeDefs: typeDefs,
resolvers
})
const server = new ApolloServer({
schema: schema
})
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}.`)
})
有什么方法可以简单地加载看起来像这样的.graphql吗? schema.graphql
Is there any way to simply load a .graphql that looks as such?
schema.graphql
type CourseType {
_id: String!
name: String!
}
type Query {
courseType(_id: String): CourseType
courseTypes: [CourseType]!
}
然后将其解析为 index.js
?我注意到 graphql-yoga
支持此功能,但想知道 apollo-server
是否支持.我在文档中的任何地方都找不到它.我也无法使 fs.readFile
正常工作.
Then it would be parsed in the index.js
? I noticed that graphql-yoga
supports this, but was wondering if apollo-server
does. I cannot find it anywhere in the docs. I can't get fs.readFile
to work either.
推荐答案
如果在 .graphql
文件中定义类型定义,则可以通过以下几种方式之一进行读取:
If you define your type definitions inside a .graphql
file, you can read it in one of several ways:
1.)自己读取文件:
1.) Read the file yourself:
const { readFileSync } = require('fs')
// we must convert the file Buffer to a UTF-8 string
const typeDefs = readFileSync('./type-defs.graphql').toString('utf-8')
2.)利用 graphql-tools
之类的库为您完成此操作:
2.) Utilize a library like graphql-tools
to do it for you:
const { loadDocuments } = require('@graphql-tools/load');
const { GraphQLFileLoader } = require('@graphql-tools/graphql-file-loader');
// this can also be a glob pattern to match multiple files!
const typeDefs = await loadDocuments('./type-defs.graphql', { file
loaders: [
new GraphQLFileLoader()
]
})
3.)使用 babel插件或 webpack加载程序
import typeDefs from './type-defs.graphql'
这篇关于如何使用apollo-server加载.graphql文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!