Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// 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);
Result
Open