Apollo GraphQL - Import .graphql schema as typeDefs

跟風遠走 提交于 2020-01-05 03:50:08

问题


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?

If there isn't, how does one import the typeDefs from an external .graphql file?


回答1:


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



回答2:


You can use the function makeExecutableSchema to pass in the typeDefs. Something like this:

import { makeExecutableSchema } from 'graphql-tools';
import mySchema from './src/schema.graphql';

const app = express();

const schema = makeExecutableSchema({
  typeDefs: [mySchema],
  resolvers: {
    ...
  },
});

app.use(
  '/graphql',
  graphqlExpress({ schema })
);


来源:https://stackoverflow.com/questions/53385525/apollo-graphql-import-graphql-schema-as-typedefs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!