Skip to content

Instantly share code, notes, and snippets.

@mandado
Created August 1, 2017 01:46
Show Gist options
  • Save mandado/6d2f5b5490c268c7dfd0693385458e19 to your computer and use it in GitHub Desktop.
Save mandado/6d2f5b5490c268c7dfd0693385458e19 to your computer and use it in GitHub Desktop.
injecting user on context graphql
'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