Created
August 5, 2022 13:00
-
-
Save ziedHamdi/87d67701d7bfcafc4049bd73e9689e01 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
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