I need help interpreting a piece of code.
I have been attempting to learn how to authenticate users with jwt and returning tokens and refresh tokens.
It has been a fun ride and I came across this repository where the user added an extension/chain function which as far as I understand combines multiple graphql resolvers:
// I don't understand this function
const createResolver = (resolver) => {
const baseResolver = resolver;
baseResolver.createResolver = (childResolver) => {
const newResolver = async (parent, args, context, info) => {
await resolver(parent, args, context, info);
return childResolver(parent, args, context, info);
};
return createResolver(newResolver);
};
return baseResolver;
};
export const requiresAuth = createResolver((parent, args, context) => {
if (!context.user || !context.user.id) {
throw new Error('Not authenticated');
}
});
export const requiresAdmin = requiresAuth.createResolver((parent, args, context) => {
if (!context.user.isAdmin) {
throw new Error('Requires admin access');
}
});
it is used like this:
Query: {
getBook: requiresAuth.createResolver((parent, args, { models }, info) =>
// do something fun
),
}
I don't understand the createResolver function and I am asking if this is some type of programming paradigm where there are articles that I can read and understand it better.
Googling I did find graphql-resolvers which as far as I understand does the same thing but in this case, I would need to install yet another package which I would like to avoid but at the same time, I don't want to use a function that I don't fully understand.
Edit:
What I understand of the function/think I understand:
chains multiple functions together by calling one function and then inside of that function passing in a new function: requiresAuth.createResolver
Inside of the function itself I'm having trouble figuring it out.
We get a new variable baseResolver which we chain a new createResolver
where we then recursively call the parent function.
I can't understand the flow of this I guess.