Last active
March 18, 2019 10:26
-
-
Save timjbray/1847e1b9a8544fc24fca907d36a273b7 to your computer and use it in GitHub Desktop.
This file contains 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
const server = new ApolloServer({ | |
typeDefs, | |
resolvers, | |
context: graphQLContext | |
}); | |
const graphQLContext = (context) => { | |
const { req, res } = context; | |
// use a express middleware to auth user | |
const isAuthenticated = Boolean(req.user); | |
const { name, operation } = getOperationName(req); | |
// Check here if this a public operation | |
if (!isAuthenticated && !isPublicOperation(name, operation)) { | |
throw new AuthenticationError('Not authenticated.'); | |
} | |
// Could also check role based authorization | |
return { | |
currentUser: req.user, | |
isAuthenticated | |
}; | |
}; | |
const getOperationName = (req) => { | |
const query = req.body.query; | |
// use gql to parse the given query/mutation | |
const op = gql` | |
${query} | |
`; | |
// this is the name the user gave for the operation | |
const operationNameDefault = get(req, 'body.operationName'); | |
// this is the name of the actual operation | |
const name = get(op, 'definitions[0].selectionSet.selections[0].name.value') || operationNameDefault; | |
const operation = get(op, 'definitions[0].operation') || ''; | |
return { name, operation }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment