Skip to content

Instantly share code, notes, and snippets.

@ziedHamdi
Created August 5, 2022 13:00
Show Gist options
  • Save ziedHamdi/87d67701d7bfcafc4049bd73e9689e01 to your computer and use it in GitHub Desktop.
Save ziedHamdi/87d67701d7bfcafc4049bd73e9689e01 to your computer and use it in GitHub Desktop.
import {setUserAccessToken} from "../facebook";
import {Session, User} from '../db'
import jwt from 'jsonwebtoken'
import {TOKEN_SECRET} from "../constants/other";
import logger from "../../lib/logger";
const GraphQlSchema = require('../graphql').default
const {graphqlHTTP} = require('express-graphql');
const setFbToken = (req, res, next) => {
setUserAccessToken(req.user)
next()
}
function formatError(error) {
const errorDetails = error.message.startsWith("{") ? JSON.parse(error.message) : error.message
return {
message: errorDetails.text,
locations: error.locations,
stack: error.stack ? error.stack.split('\n') : [],
path: error.path,
errorCode: errorDetails.code ?? 500,
"zied?": "who else?"
}
}
const graphQlServer = graphqlHTTP(async (req, res, graphQLParams) => {
// console.log("##########################request headers: ", req.headers)
let user = null
//FIXME externalize this part to an auth function that calls next(error) if user is not authenticated
const infraToken = req.header('infra-token')
// console.log( "infra token : ", JSON.stringify(infraToken), " - secret: '", TOKEN_SECRET +"'")
if (!infraToken || infraToken.trim().length == 0) {
// user not logged
} else {
try {
user = jwt.verify(infraToken, TOKEN_SECRET)?.data
// console.log( "user from token : ", user)
//FIXME (for some reason I have to load the user from db)
// logger.debug("####### user ", user, " ######### FIXME (for some reason I have to load the user from db)")
user = await User.findById(user._id)
// logger.debug("####### user ", user)
} catch (err) {
logger.error(err.message)
console.trace()
}
}
return {
schema: GraphQlSchema,
// graphiql: process.env.NODE_ENV !== 'production',
graphiql: true,
customFormatErrorFn: formatError,
context: {
user,
sessionID: req.sessionID
},
}
});
function addGraphqlRoute(app, url) {
app.use(url ? url : '/api/graphql', graphQlServer)
}
export {addGraphqlRoute}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment