Exclude resolvers
zenVentzi opened this issue · comments
For example there are 30 resolvers and we know that 27 of them need auth middleware and only 3 of them don't. The way that I know about from the docs is to specify all the 27 resolvers that require the middleware. Is there a way to do the opposite, i.e. write only the 3 resolvers to be excluded for the auth middleware?
@zenVentzi I agree with you. Currently, I am in the same situation and from the docs, it seems like there is no way to exclude queries or mutations from the middleware. If you have access to the queries and mutations types you can workaround writing same middleware for every query and mutation with dynamic generated one like this:
`
const generateMiddlewareForMutations = () => {
const mutationMiddleware = {};
Object.keys(mutationType.fields).map(key => {
if (key !== "authorization") {
mutationMiddleware[key] = (resolve, parent, args, context, info) => {
// apply middleware
return resolve(parent, args, context, info);
}
}
});
return mutationMiddleware;
}
const authorizationMiddleware = {
QueryType: {
...generateMiddlewareForQueries()
},
MutationType: {
...generateMiddlewareForMutations()
}
}
`
Hi @zenVentzi here's my solution to this problem.
You can see better in this repository: https://github.com/wendelfreitas/kraken
AuthMiddleware.js
import { applyMiddlewareRule } from '../../utils/common';
import resolvers from '../resolvers';
const Auth = () => {
/* All my middleware function */
}
export default {
/*
* Auth: is a Middleware function above
* Resolvers.Query: my query object with all resolvers
* exceptions: array of resolvers exceptions (name of resolvers that middleware will not be applied)
*/
Query: applyMiddlewareRule(Auth, Resolvers.Query, exceptions),
Mutation: applyMiddlewareRule(Auth, Resolvers.Mutation), // No exceptions example
};
common.js
const mergeRuleInResolvers = (rule, resolvers, exceptions) => {
/* Removes resolvers that are in exceptions and apply the rule to all others */
let newResolvers = resolvers
.filter(resolver => !exceptions.includes(resolver))
.map(resolver => ({ [`${resolver}`]: rule }));
/* Assign in only one object */
newResolvers = Object.assign({}, ...newResolvers);
return newResolvers;
};
/* Apply middleware rule in all resolvers of the 'type' received */
export const applyMiddlewareRule = (rule, type, exceptions = []) => {
/* Transform resolvers queries in array */
let resolvers = type instanceof Object ? Object.keys(type) : [];
resolvers = mergeRuleInResolvers(rule, resolvers, exceptions);
return resolvers;
};
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.