Pitchlyapp / meteor-apollo2

An example showing how to use Apollo 2.0 with GraphQL server + subscriptions
20 stars 4 forks source link

Use new Apollo concepts and syntax #6

Open tab00 opened 6 years ago

tab00 commented 6 years ago

There have been many updates to Apollo and Meteor-Apollo.

Particularly, you no longer need to create a SubscriptionServer.

Please update this example to adapt to the changes.

Here's some example code:

  const server = new ApolloServer({
    typeDefs,
    resolvers,
    dataSources: () => ({
      dsBooks: new DSBooks()
    }),
    context: async ({ req, connection }) => {
      if (connection) {
        const token = req.headers.authorization || ""
        return { token }
      }
    },
    subscriptions: {
      path: "/subscriptions",
      onConnect: async (connectionParams, webSocket, context) => { //connectionParams has authToken that was set in WebSocketLink on client
        console.log(`Subscription client connected using built-in SubscriptionServer.`)
        console.log(`connectionParams: ${JSON.stringify(connectionParams)}`)

        if (connectionParams.authToken) return { user: await getUser(connectionParams.authToken) } //puts user into subscription context so that it can be used with withFilter()

        // throw new Error('Missing auth token. Please log in.')
      },
      onDisconnect: async (webSocket, context) => {
        console.log(`Subscription client disconnected.`)
      }
    }
  })

  import { WebApp } from 'meteor/webapp'
  server.applyMiddleware({ app: WebApp.connectHandlers }) //path option defaults to /graphql
  WebApp.connectHandlers.use('/graphql', (req, res) => { if (req.method === 'GET') res.end() }) // To prevent server-side exception "Can't set headers after they are sent" because GraphQL Playground (accessible in browser via /graphql) sets headers and WebApp also sets headers

server.installSubscriptionHandlers(WebApp.httpServer)
michaelcbrook commented 6 years ago

I have tried these new changes as of a few days ago. While it works, I ran into another issue where I needed to stop GraphQL websockets from conflicting with Meteor's websocket, and the fix unfortunately required direct access to SubscriptionServer. Until I can find a way to do this in the newest version, I still recommend using the old version for now. I'll update here when it seems safe to upgrade.