Permalink
Browse files

Add HTTP Caching to Express Server

  • Loading branch information...
kevinjalbert committed Jul 4, 2018
1 parent 5cbb630 commit 0bf8d6bccc5649b00dda77b4dfdce523c22b4796
Showing with 6 additions and 5 deletions.
  1. +4 −2 express-graphql/persistedQueriesMiddleware.js
  2. +2 −3 express-graphql/server.js
@@ -3,16 +3,18 @@ const extractedQueries = invert(require('./extracted_queries.json'))
persistedQueriesMiddleware = (req, res, next) => {
console.log("Handling request to: " + req.url)
res.set('Cache-Control', 'public, max-age=10')
const querySignature = req.body.extensions.persistedQuery.sha256Hash;
const extensions = JSON.parse(req.query.extensions)
const querySignature = extensions.persistedQuery.sha256Hash;
const persistedQuery = extractedQueries[querySignature]
if (!persistedQuery) {
res.status(400).json({ errors: ['Invalid querySignature'] })
return next(new Error('Invalid querySignature'))
}
req.body.query = persistedQuery
req.query.query = persistedQuery
next()
}
@@ -1,5 +1,4 @@
const { GraphQLServer } = require('graphql-yoga')
const bodyParser = require('body-parser');
const { typeDefs } = require('./graphql/typeDefs')
const { resolvers } = require('./graphql/resolvers')
@@ -8,12 +7,12 @@ const { persistedQueriesMiddleware } = require('./persistedQueriesMiddleware')
const server = new GraphQLServer({ typeDefs, resolvers })
const options = {
port: 5000,
getEndpoint: true,
endpoint: '/graphql',
playground: '/playground',
}
server.express.use(bodyParser.json());
server.express.post('/graphql', persistedQueriesMiddleware)
server.express.get('/graphql', persistedQueriesMiddleware)
server.start(options, ({ port }) =>
console.log(
`Server started, listening on port ${port} for incoming requests.`,

0 comments on commit 0bf8d6b

Please sign in to comment.