Let's imagine having a simple type in graphql
type Coupon {
id: ID!
code: String!
}
I'd love to show the id field only if a user has a determinate condition. I'll then create a directive
directive IncludeWhen(cond: String!) on FIELD_DEFINITION
and edit the code as
type Coupon {
id: ID! @IncludeWhen(cond: "ADMIN")
code: String!
}
I'll check in the directive resolver if the user has necessary privileges:
export class IncludeWhenDirective extends SchemaDirectiveVisitor {
public visitFieldDefinition(field) {
const { resolve = defaultFieldResolver } = field;
const requiredCond = this.args.cond;
field.resolve = async function (...args) {
const context = args[2];
const currentUser = context.currentUser;
let result;
if (currentUser.hasCond(requiredCond) {
throw new AuthenticationError();
result = await resolve.apply(this, args);
}
return result;
};
}
}
Well, this is wrong. Endpoint return an error like
Cannot return null for non-nullable field Coupon.ID
when queried from a user without required condition.
Is it possible to skip this field entirely? Maybe accessing the resolver and deleting the fields without breaking the whole thing up?
!
) field (you can't change type on demand, otherwise server will throw error 'null for not nullable'). - return FAKE - if fake (detect on client) not show?.But it can lead to client cache error if you use a const for id of items in array ... return random number above some limit? IMHO should be not requestable and client shoul be aware of that (not hard to implement). – xadm