Last active
May 26, 2020 09:05
-
-
Save danielres/b62a9ad55152ec47822974a7dfe07255 to your computer and use it in GitHub Desktop.
using express js middlewares in apollo server graphql context
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 { ApolloServer, gql } from "apollo-server-micro" | |
import cookieSession from "cookie-session" | |
const ONE_HOUR = 60 * 60 * 1000 | |
const typeDefs = gql` | |
type Query { | |
hello: String! | |
} | |
` | |
const resolvers = { | |
Query: { | |
hello: (parent, args, { session }) => { | |
// 3) session from cookieSession is now available to all resolvers through context and can be read or updated: | |
session.views = (session.views || 0) + 1 | |
return `Hello! Views: ${session.views}` | |
}, | |
}, | |
} | |
const apolloServer = new ApolloServer({ | |
typeDefs, | |
resolvers, | |
context: ({ req, res }) => { | |
// 1) We invoke the middleware with (req, res, () => {}) | |
cookieSession({ | |
name: "session", | |
keys: ["key1", "key2"], | |
maxAge: 24 * ONE_HOUR, | |
})(req, res, () => {}) | |
// 2) req is now mutated by cookieSession (cookieSession adds .session to req) | |
// we can pass session to all resolvers through the context object: | |
return { session: req.session } | |
}, | |
}) | |
const handler = apolloServer.createHandler({ path: "/api/graphql" }) | |
export const config = { | |
api: { | |
bodyParser: false, | |
}, | |
} | |
export default handler |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment