GraphQL
Beginner
1 min read
Resolver Middleware with graphql-middleware
Example
// npm install graphql-middleware graphql-shield
import { applyMiddleware } from 'graphql-middleware';
import { shield, rule, and, or, not, allow, deny } from 'graphql-shield';
import { makeExecutableSchema } from '@graphql-tools/schema';
// Rules
const isAuthenticated = rule({ cache: 'contextual' })(
async (parent, args, { currentUser }) => currentUser !== null
);
const isAdmin = rule({ cache: 'contextual' })(
async (parent, args, { currentUser }) => currentUser?.role === 'ADMIN'
);
const isPostOwner = rule({ cache: 'strict' })(
async (parent, { id }, { currentUser, db }) => {
const post = await db.posts.findById(id);
return post?.authorId === currentUser?.id;
}
);
// Permissions matrix
const permissions = shield({
Query: {
me: isAuthenticated,
users: isAdmin,
post: allow, // public
},
Mutation: {
createPost: isAuthenticated,
updatePost: or(isAdmin, isPostOwner),
deletePost: or(isAdmin, isPostOwner),
adminAction: and(isAuthenticated, isAdmin),
},
});
// Apply middleware to schema
const baseSchema = makeExecutableSchema({ typeDefs, resolvers });
export const schema = applyMiddleware(baseSchema, permissions);
Related Resources
GraphQL Reference
Complete tag & property list
GraphQL How-To Guides
Step-by-step practical guides
GraphQL Exercises
Practice what you've learned
More in GraphQL