Search code examples
websocketgraphqlexpress-graphqlgraphql-subscriptions

apollo explorer say "isTrusted": true when i try use Subscription


guys, I have a problem when I want to use a Subscription I'm facing this issue I don't find a solution in any place, I'm a GQL user and i decide to use Subscription to make real-time website but I'm facing a a this issue , hare is code

I'm trying to show apollo docs but I'm facing another issue(graphql doesn't find my resolver), so I try to use this pace of code in my mind it's work but the issue is it says Unable to connect wss://localhost:4001 also I'm trying to use Unable to connect wss://localhost:4001/graphql and Unable to connect wss://localhost:4001/subscription, also i try this three way with using ws

// my resolver
const somethingChanged = () => {
  // subscribe: () => {
  console.log("subscribe")
  pubsub.asyncIterator(SOMETHING_CHANGED_TOPIC)
  // }
}

const makeId = () => {
  // make id generator 36 symbols
  let id = Math.random().toString(36).split(".")[1]
  pubsub.publish(SOMETHING_CHANGED_TOPIC, {
    somethingChanged: {
      id,
    },
  })
  return id
}

const resolvers = {
  Subscription: {
    somethingChanged,
  },
  Query: {
    hello: () => "Hello world!",
  },
  Mutation: {
    makeId,
  },
}
// app.ts
import { createServer } from "http"
import express from "express"
import { ApolloServer, gql } from "apollo-server-express"
import { typeDefs } from "./graphql/schema"
import "colors"
import resolvers from "./graphql/root"
import connect from "./db/connect"
import { PubSub } from "graphql-subscriptions"

const SOMETHING_CHANGED_TOPIC = "something_changed"

require("dotenv").config()
export const pubsub = new PubSub()

// 1  creating  one function for app
const startServer = async () => {
  // 2 // declaring app as express
  const app = express()
  const httpServer = createServer(app)

  setInterval(() => {
    console.log(`Server was work ${Math.random().toString()}`.green)
  }, 2000)

  // middleware's
  connect()

  // 5
  const apolloServer = new ApolloServer({
    typeDefs,
    resolvers,
    context: ({ req }) => req,
  })

  // 6
  await apolloServer.start()

  // 7
  apolloServer.applyMiddleware({
    app,
    path: "/graphql",
  })

  // 8
  httpServer.listen({ port: process.env.PORT || 4001 }, () =>
    console.log(
      `Server listening on localhost:4001${apolloServer.graphqlPath}`.blue
    )
  )
}

startServer()


I just want to test in apollo explorer but it doesn't work


Solution

  • I think you missed some of the steps please follow this code

    import { ApolloServer } from "apollo-server-express"
    import { ApolloServerPluginDrainHttpServer } from "apollo-server-core"
    import express from "express"
    import graphSchema from "./graphql/schema"
    import resolvers from "./graphql/resolvers"
    import { createServer } from "http"
    import connect from "./db/db"
    import "colors"
    import { makeExecutableSchema } from "@graphql-tools/schema"
    import { execute, subscribe } from "graphql"
    import { SubscriptionServer } from "subscriptions-transport-ws"
    import getUser from "./helpers/getUser"
    import { setUserData, userData, Req, setReq } from "./helpers/localData"
    import cors from "cors"
    require("dotenv").config()
    const PORT = process.env.PORT || 4003
    const startServer = async () => {
      const schema = makeExecutableSchema({ typeDefs: graphSchema, resolvers })
      const app = express()
      const httpServer = createServer(app)
      const subscriptionServer = SubscriptionServer.create(
        {
          schema,
          execute,
          subscribe,
        },
        { server: httpServer, path: "/graphql" }
      )
    
      setInterval(() => {
        console.log(
          `Server was work, on port ${PORT}, time ${
            new Date().toLocaleTimeString().blue
          } , process pid: ${process.pid}`.green
        )
      }, 2000)
      app.use(cors())
      // database connected
      connect()
      // apollo server was created
      const apolloServer = new ApolloServer({
        typeDefs: schema,
        resolvers,
        schema,
        // context
        context: async ({ req }) => {
          setReq(req)
          const token = req.headers.authorization || ""
          const user = (await getUser(token)) || ""
          setUserData(user)
          return { user, req }
        },
        // for subscriptions
        plugins: [
          ApolloServerPluginDrainHttpServer({ httpServer }),
          {
            async serverWillStart() {
              return {
                async drainServer() {
                  subscriptionServer.close()
                },
                context: async (req: any) => {
                  const token = req.headers.authorization || ""
                  const user = await getUser(token)
                  return { user, req }
                },
              }
            },
          },
        ],
      })
      // apollo server was started
      await apolloServer.start()
    
      app.use("/api", require("./routes"))
    
      apolloServer.applyMiddleware({
        app,
        path: "/graphql",
      })
      // apollo server was start with express server
      httpServer.listen(PORT, () =>
        console.log(
          Server listening on http://localhost:${PORT}${apolloServer.graphqlPath}
            .blue
        )
      )
    }
    startServer() // start server