When trying to place Apollo graphql schema / typedefs in separate JavaScript module usually end up with the following error ?

Apollo Server requires either an existing schema, modules or typeDefs..

The structure of the project

Project
-schema
--typeDefs.js
--resolvers.js
-index.js
-package.json
// Here is the problamtic code
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const { importSchema } = require("graphql-import")
const {typeDefs} = require("./schema/TypeDefs") // as a javascript module exported
const resolvers= require("./schema/Resolvers")

const server = new ApolloServer({
typeDefs, resolvers,
plugins: [
    ApolloServerPluginLandingPageGraphQLPlayground({
        // options
    })
    , ApolloServerPluginLandingPageDisabled()
]
});

const app = express();
server.start().then(r => {
server.applyMiddleware({ app });
app.listen({ port: 3000 }, () =>
    console.log('Now browse to http://localhost:4000' + server.graphqlPath)
)
})

Solution

A quick solution for this issue is to place schema in .graphsql file and use graphql-import to import the typeDefs. We need not to export module , just the plain schema as follows.

 # ./schema/typeDefs.graphql
 
  type User{
       name:String!,
       role:String!,
       id:Int
  }

  type Query{
      getAll: [User!]!
  }

  type Mutation{
      newUser(name :String!,role:String ,id:Int):User
  }

graphql-import

Install the import module using * npm i -s graphql-import* and use ImportSchema in our index.js file as

const { importSchema } = require("graphql-import")
// const {typeDefs} = require("./schema/TypeDefs")
const resolvers= require("./schema/Resolvers")
const typeDefs = importSchema('./schema/Typedefs.graphql')
....

I hope this will help you.

Here is a list of Apollo posts that may save your time


This free site is ad-supported. Learn more