Apollo GraphQL - 将 .graphql 模式导入为 typeDefs

Mus*_*ill 5 apollo graphql apollo-server

随着graphql瑜伽,你可以简单地通过执行以下导入架构:typeDefs: './src/schema.graphql'。apollo-server-express 是否有类似的方法?

如果没有,如何从外部.graphql文件导入 typeDefs ?

Mus*_*ill 7

我通过使用grahpql-import找到了一种方法,它完全符合我的需要。请参阅下面的示例代码:

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 })
Run Code Online (Sandbox Code Playgroud)

**

更新:graphql-import v0.7+

**

importSchema现在是异步的,应该作为承诺处理。只需将它包装在一个async函数中并简单地将其包装await起来。

async function start() {
    const typeDefs = await importSchema(".src/schema.graphql")
}
Run Code Online (Sandbox Code Playgroud)