Apollo GraphQL - 将 .graphql 模式导入为 typeDefs [英] Apollo GraphQL - Import .graphql schema as typeDefs
问题描述
使用 graphql-yoga,您可以通过执行以下操作简单地导入您的模式:typeDefs: './src/schema.graphql'
.apollo-server-express 是否有类似的方法?
With graphql-yoga you can simply import your schema by doing the following: typeDefs: './src/schema.graphql'
. Is there a similar way of doing so with apollo-server-express?
如果没有,如何从外部 .graphql
文件导入 typeDefs?
If there isn't, how does one import the typeDefs from an external .graphql
file?
推荐答案
我找到了一种方法,使用 grahpql-import 这正是我所需要的.请参阅下面的示例代码:
I found a way of doing this by using grahpql-import which does exactly what I needed. See sample code below:
import { ApolloServer } from 'apollo-server-express'
import { importSchema } from 'graphql-import'
import Query from './resolvers/Query'
const typeDefs = importSchema('./src/schema.graphql')
const server = new ApolloServer({
typeDefs,
resolvers: {
Query
}
})
const app = express()
server.applyMiddleware({ app })
app.listen({ port: 4000 })
**
更新:graphql-import v0.7+
**
importSchema
现在是异步的,应该作为承诺处理.只需将其包装在 async
函数中,然后简单地 await
即可.
importSchema
is now async and should be handled as a promise. Just wrap it in a async
function and simply await
it.
async function start() {
const typeDefs = await importSchema(".src/schema.graphql")
}
这篇关于Apollo GraphQL - 将 .graphql 模式导入为 typeDefs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!