Reputation: 1958
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?
Upvotes: 6
Views: 6289
Reputation: 406
Updated: 06/2023
Using @graphql-tools/merge
const { mergeTypeDefs } = require('@graphql-tools/merge')
const clientType = require('./clientType')
const productType = require('./productType')
const types = [clientType, productType]
module.exports = mergeTypeDefs(types)
Upvotes: 0
Reputation: 1958
I found a way of doing this by using graphql-import which does exactly what I need. 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 })
**
UPDATE: graphql-import v0.7+
**
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")
}
Upvotes: 8
Reputation: 188
As a more recent response, following the top of the tutorial here link one can move the schema to a new file called schema.graphql and then import "fs" and "path" and input in the file so now it looks like:
const fs = require('fs');
const path = require('path');
const server = new ApolloServer({
typeDefs: fs.readFileSync(
path.join(__dirname, 'schema.graphql'),
'utf8'
),
resolvers,
})
Upvotes: 0
Reputation: 5765
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 })
);
Upvotes: 4