GraphQL server implementation with Redis backing allowing pubsub
This repository includes a working (as of Feb 23, 2018) Apollo GraphQL server implementation providing subscriptions with Redis backing. After scouring various articles and documents, I finally got it working and felt there needs to be a concise HOWTO for what will be a very popular use case.
In a new product, we wanted realtime notifications to users, and planned on adding a Redis user cache. Our UI is built with React and Redux, so we decided on GraphQL as the API layer (instead of REST), and wanted to leverage the new subscriptions feature, or at least compare it to polling.
npm
)Clone and install the app
git clone git@github.com:mikesparr/tutorial-graphql-subscriptions-redis.git
cd tutorial-graphql-subscriptions-redis
npm install
Add local ENV variables (I use dotenv
or .env
file)
# environment variables for application
export SERVER_PORT=3000
export REDIS_HOST=localhost
export REDIS_PORT=6379
Make sure Redis is running
brew install redis && brew services start redis
Start the server
npm start
Open browser (1) to http://localhost:3000/graphiql
Open another browser (2) tab to same URL
Open terminal window (1) to Redis monitor
redis-cli monitor
Open second terminal window (2) to execute Redis CLI commands
In browser (1), subscribe to messages (paste in graphiql and run)
subscription {
messageAdded {
id
content
}
}
In browser (2), publish (mutate) a message (paste in graphiql and run)
mutation {
addMessage(message: "Hello World")
}
In terminal window (1) confirm publish messages appear
In browser (1), confirm message appears
In terminal window (2) publish new message
redis-cli PUBLISH "messageAdded" '{"messageAdded": {"id": "555", "content": "Hello Redis"}}'
Confirm terminal (1) and browser (1) messages appear
Congratulations! Your GraphQL server delivered subscription messages to a client from both mutations and new messages directly into Redis!
server.js
for web socket connpubsub.subscribe()