Created
August 1, 2017 01:46
-
-
Save mandado/6d2f5b5490c268c7dfd0693385458e19 to your computer and use it in GitHub Desktop.
injecting user on context graphql
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
'use strict'; | |
const { graphqlHapi, graphiqlHapi } = require('apollo-server-hapi'); | |
const jwt = require('jsonwebtoken'); | |
const schema = require('./schema'); | |
const db = require('./config/database'); | |
const secretJWT = 'minhasecreetjwt'; | |
exports.register = function (server, options, next) { | |
let context = { | |
secretJWT, | |
user: null | |
}; | |
server.ext('onRequest', async (request, reply) => { | |
if (request.headers.authorization) { | |
const { data: { id } } = jwt.verify(request.headers.authorization, secretJWT); | |
const userDB = await db('users').where({ id }).first([ | |
'id', 'name' | |
]); | |
context.user = userDB; | |
} | |
return reply.continue(); | |
}); | |
server.register({ | |
register: graphqlHapi, | |
options: { | |
path: '/graphql', | |
graphqlOptions: { | |
schema, | |
context | |
}, | |
route: { | |
cors: true | |
} | |
}, | |
}); | |
server.register({ | |
register: graphiqlHapi, | |
options: { | |
path: '/graphiql', | |
graphiqlOptions: { | |
endpointURL: '/graphql', | |
schema, | |
}, | |
route: { | |
cors: true | |
} | |
}, | |
}); | |
next(); | |
}; | |
exports.register.attributes = { | |
pkg: require('../package.json') | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment