Skip to content

Instantly share code, notes, and snippets.

View shrirambalakrishnan's full-sized avatar

Shriram shrirambalakrishnan

View GitHub Profile
const { rule, shield } = require('graphql-shield')
// Rules
const isUser = rule({ cache: 'contextual' })(
async (parent, args, ctx, info) => {
let isUser = ctx.user.roles.includes('USER');
console.log(`isUser = ${isUser}`);
return isUser;
}
)
const { AuthDirective } = require("./src/directives/auth")
// The GraphQL schema
const typeDefs = gql`
directive @auth(
requires: Role = ADMIN
) on FIELD_DEFINITION | OBJECT
enum Role {
ADMIN
REVIEWER
const { SchemaDirectiveVisitor } = require("apollo-server");
const { defaultFieldResolver } = require("graphql");
class AuthDirective extends SchemaDirectiveVisitor {
visitObject(type) {
this.ensureFieldsWrapped(type);
type._requiredAuthRole = this.args.requires;
}
// Visitor methods for nested types like fields and arguments
// also receive a details object that provides information about
const typeDefs = gql`
input PostInputType {
id: Int!
title: String!
description: String
}
type CommentType {
id: Int!
comment: String!
}
const resolvers = {
UserType: {
posts: (parent, _, ctx) => {
return ctx.postsLoader.load(parent.id);
}
},
Query: {
users: async () => {
try {
return await User.findAll()
const resolvers = {
UserType: {
posts: (parent) => {
return postsLoader.load(parent.id);
}
},
Query: {
users: async () => {
try {
return await User.findAll()
const DataLoader = require('dataloader');
const postsLoader = new DataLoader( async (userIds) => {
// Assume, userIds = [ 1, 2 ]
let posts = await Post.findAll( { where: { userId: userIds } } );
// posts = [ {title: "A", userId: 1}, {title: "B", userId: 1}, {title: "C", userId: 2} ]
let postsGroupedByUser = userIds.map ( userId => {
return posts.filter( post => post.userId == userId );
const resolvers = {
UserType: {
posts: async (parent) => {
return await Post.findAll({where: {userId: parent.id}});
}
},
Query: {
users: async () => {
try {
return await User.findAll()
const resolvers = {
Query: {
users: async () => {
try {
let users = await User.findAll()
let userIds = users.map( user => user.id)
let posts = await Post.findAll({where: {userId: userIds}});
let usersData = users.map( user => {
const typeDefs = gql`
type PostType {
title: String
description: String
}
type UserType {
id: Int
name: String
email: String