import { Database } from './db' import { GraphQLError} from 'graphql' import { VerifyToken } from './auth'; export const ContextBuilder = async ( dbs , extend ) => { return ({ req }) => { //try to retrieve auth & getUser functions from extend const { getUser, error, auth } = extend; let user; if ( auth && auth == true) { // get the user token from the headers const token = req.headers.authentication || ''; // try to retrieve a user with the token user = VerifyToken(token); // optionally block the user // we could also check user roles/permissions here if (!user) throw new GraphQLError('you must be logged in to query this schema'); } else { return { user: user || null, dbs, ...extend, } } } } export const StackBuilder = (config, extend = null) => { //Load Models //const db = new DatabaseStack(config) const db = Database(config); //Build Context const context = ContextBuilder( db , ( extend ? extend : {} )) return { context, db, } }