Hovhannes Amirjanyan
Hovhannes Amirjanyan

Reputation: 83

How to pass arguments to graphqlHTTP middleware

how can i pass arguments to graphqlHTTP middleware

I'm trying to pass Authorization header token payload to graphqlHTTP middleware from another upper level middleware

app.use('/private', (req:Request,res:Response,next:Function) => {

   if(!req.header('Authorization')){
      res.json({
         error:true,
         message:'Authorization bearer required'
      })
   }else{
      const token = Buffer.from(req.header('Authorization').split('Bearer ')[1], 'base64').toString('ascii');
      if(decode(token)){
         next();
      }else{
         res.json({
            error:true,
            message:'Authorization bearer required'
         })
      }
   }
});

app.use('/private', graphqlHTTP({
   schema:privateSchema,
   graphiql:false
}))

Upvotes: 1

Views: 1517

Answers (2)

mmstarz
mmstarz

Reputation: 221

recently tried this and it works:

jwtAuth - middleware that checks authorizaion header for token. Decodes it and store credentials in req.auth.

files map

...
[graphql]
[utils]
index.js

index.js

...

const graphqlSettings = require("./graphql/settings");
const jwtAuth = require("./utils/jwtAuth");
// init
...
// parser
...
// cors setup
...        
// JWT authentication
app.use(jwtAuth);    
// graphql init
app.use("/graphql", graphqlSettings);
...

settings.js

...
const { graphqlHTTP } = require("express-graphql");
const typeDefs = require("./typeDefs");
const resolvers = require("./resolvers");
// models
...
// extend context with models
const models = {
    ...
};

module.exports = graphqlHTTP((req) => ({
    graphiql: true,
    schema: typeDefs,
    rootValue: resolvers,
    context: {
        ...models,
        auth: req.auth,
    },
}));

Upvotes: 1

christian
christian

Reputation: 1705

It's common to set data from a middleware within the request itself.

In your scenario, the token can be set as req.token and then passed to your graphql resolver context like:

// main.js

app.use(authMidddleware) // sets req.token
app.use(
  '/graphql',
  bodyParser.json(),
  graphqlExpress(req => ({ schema, context: req }))
)

// some-resolver.js
export const myResolver = {
  Query: {
    token: async (parent, { input }, context) => {
      const { token } = context;
      // other stuff
    }
  }
}

Upvotes: 1

Related Questions