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
Then using it for the apollo-server
:
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}.`)
})
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]!
}
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.
If you define your type definitions inside a .graphql
file, you can read it in one of several ways:
1.) Read the file yourself:
const { readFileSync } = require('fs')
// we must convert the file Buffer to a UTF-8 string
const typeDefs = readFileSync(require.resolve('./type-defs.graphql')).toString('utf-8')
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.) Use a babel plugin or a webpack loader
import typeDefs from './type-defs.graphql'