Created
October 30, 2021 10:09
-
-
Save Dajust/bce513fac1800a4e366d978f6c11f743 to your computer and use it in GitHub Desktop.
Apollo GraphQL Subscription issues
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createServer } from 'http'; | |
import { execute, subscribe } from 'graphql'; | |
import { SubscriptionServer } from 'subscriptions-transport-ws'; | |
import { makeExecutableSchema } from '@graphql-tools/schema'; | |
import express from 'express'; | |
import { ApolloServer } from 'apollo-server-express'; | |
import { gql } from 'apollo-server-core'; | |
import { PubSub } from 'graphql-subscriptions'; | |
let currentNumber = 0; | |
const typeDefs = gql` | |
type Query { | |
currentNumber: Int | |
} | |
type Subscription { | |
incremented: Int | |
} | |
`; | |
const resolvers = { | |
Query: { | |
currentNumber() { | |
return currentNumber; | |
}, | |
}, | |
Subscription: { | |
incremented: { | |
subscribe: () => pubsub.asyncIterator('NUMINCREMENTED'), | |
}, | |
}, | |
}; | |
const pubsub = new PubSub(); | |
(async function () { | |
const app = express(); | |
const httpServer = createServer(app); | |
const schema = makeExecutableSchema({ | |
typeDefs, | |
resolvers, | |
}); | |
const subscriptionServer = SubscriptionServer.create( | |
{ | |
schema, | |
execute, | |
subscribe, | |
onConnect(connectionParams, webSocket, context) { | |
console.log(connectionParams); | |
console.log('Connected!'); | |
return context; | |
}, | |
onDisconnect(webSocket, context) { | |
console.log('Disconnected!'); | |
}, | |
}, | |
{ server: httpServer } | |
); | |
const server = new ApolloServer({ | |
schema, | |
plugins: [ | |
{ | |
async serverWillStart() { | |
return { | |
async drainServer() { | |
subscriptionServer.close(); | |
}, | |
}; | |
}, | |
}, | |
], | |
}); | |
await server.start(); | |
server.applyMiddleware({ app }); | |
const PORT = 4000; | |
httpServer.listen(PORT, () => { | |
console.log(`Server is now running on http://localhost:${PORT}/graphql`); | |
function incrementNumber() { | |
currentNumber++; | |
pubsub.publish('NUMBER_INCREMENTED', { | |
numberIncremented: currentNumber, | |
}); | |
setTimeout(incrementNumber, 1000); | |
} | |
incrementNumber(); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment