2

I'm using apollo-server-express to create backend apis with GraphQL

Now, I want to Write GraphQL Schema in a separate file. e.g. "schema.graphql", So when I put the same code as I wrote in Template String before. into the "schema.graphql" My application is crashed with below error:

Unable to find any GraphQL type definitions for the following pointers

Error Image
(source: googleapis.com)

Here is my code :

server.js

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const { importSchema } = require('graphql-import');
const fs = require('fs');
const path = '/graphql';


const apolloServer = new ApolloServer({
  typeDefs: importSchema('./greet.graphql'),
  resolvers: require('./graphql/resolver'),
});

const app = express();
apolloServer.applyMiddleware({ app, path });

app.listen(8080, () => {
  console.log('Server Hosted');
}); 

greet.graphql

type Query {
  greeting: String
}

resolver.js

const Query = {
  greeting: () => 'Hello World From NightDevs',
};

module.exports = { Query };

Not only this, but Ive tried this solution also - Stackoverflow Solution

But This doesn't work at all

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Manav Oza
  • 35
  • 1
  • 6

1 Answers1

1

Works fine for me. package versions:

"apollo-server-express": "^2.12.0",
"graphql-import": "^0.7.1",

Example:

server.js:

const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const { importSchema } = require('graphql-import');
const path = require('path');

const apolloServer = new ApolloServer({
  typeDefs: importSchema(path.resolve(__dirname, './greet.graphql')),
  resolvers: require('./resolver')
});

const app = express();
const graphqlEndpoint = '/graphql';
apolloServer.applyMiddleware({ app, path: graphqlEndpoint });

app.listen(8080, () => {
  console.log('Server Hosted');
});

greet.graphql:

type Query {
  greeting: String
}

resolver.js:

const Query = {
  greeting: () => 'Hello World From NightDevs',
};

module.exports = { Query };

Testing via curl:

curl 'http://localhost:8080/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: http://localhost:8080' --data-binary '{"query":"query {\n  greeting\n}"}' --compressed

Get result:

{"data":{"greeting":"Hello World From NightDevs"}}
Lin Du
  • 88,126
  • 95
  • 281
  • 483