Reputation: 443
I have multiple graphql
query types. I wish to apply middleware to one query type only for authentication. Is this possible?
Something like this
app.use(
'/s',
(request, response, next) => {
if (request.body.message === 'delete') {
auth();
}
next();
},
graphqlHTTP({
schema: require('./r/s').schema(),
graphiql: true,
})
);
The issue is that the format of the body is not JSON.
Maybe I am taking the wrong approach.
Upvotes: 2
Views: 1349
Reputation: 11
Yeah, actually you can accomplish that by using graphql-middleware library.
you just define the middleware and then attach it to a specific Query or Mutation. a grqphql middleware works as a resolver, it takes: parent, args, context, info and in addition to those it also takes "resolve" which is a function we call when the middleware finishes, pretty much like "next()" in express.
asycn function checkIfUserLoggedIn(resolve, parent, args, context, info){
// check if user logged in or not
// now we call resolve and pass the arguments to the resolver which is in our case "getSecret" Query
return resolve(parent, args, context, info)
}
const middlewares = {
Query: {
getSecret: checkIfUserLoggedIn,
},
};
const schemaWithMiddleware = applyMiddleware(
schema,
...middlewares
)
and then you edit your graphqlHTTP to:
graphqlHTTP({
schema: schemaWithMiddleware,
graphiql: true,
})
Upvotes: 1