node.jsgraphqlapolloapollo-servergraphql-federation

Context in GraphQL Apollo server running infinitely


I want header values in GraphQl Apollo server in NodeJS and for this I used context function in it, but it is running infinite times.

It is printing "abcd" infinitely in console.

console: console

code:

const server = new ApolloServer({
  schema: buildSubgraphSchema([{ typeDefs, resolvers }]),
  context:((req)=>{
    // some code
    console.log("abcd");
    return "hello"
  })
});

whole server file:

const dotenv = require('dotenv')
dotenv.config({ path: './.env' })
const mongoose = require("mongoose");
const { typeDefs } = require("./schema/user");
const { resolvers } = require("./resolvers/resolver");
const { ApolloServer } = require("apollo-server");
const {buildSubgraphSchema} = require('@apollo/subgraph')


const server = new ApolloServer({
  schema: buildSubgraphSchema([{ typeDefs, resolvers }]),
  context:((req)=>{
    // some code
    console.log("abcd");
    return "hello"
  })
});


const PORT = process.env.PORT || 5000;
mongoose.connect(
  process.env.MONGO_URI,
  { useNewUrlParser: true }
);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function () {
  console.log("Connected to MongoDB");
  server.listen(PORT, () => console.log(`Server started on port ${PORT}`));
});

Solution

  • The context function is run for every request made against the Apollo Server.

    If you're using a tool like GraphQL Playground or Apollo Studio, these will poll the schema from the server in a set interval, usually a second. Check if you have any of these tools connected to your server. If so, stop them (or close their tabs) to see if the "problem" disappears.

    If the repeated logging stops when these tools are disconnected, then there's nothing to worry about, your server is actually simply working as expected.