forked from Hganavak/graphql-server-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth-directive.js
51 lines (40 loc) · 1.83 KB
/
auth-directive.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const { SchemaDirectiveVisitor } = require("apollo-server");
const {
defaultFieldResolver,
GraphQLString,
} = require("graphql");
class AuthDirective extends SchemaDirectiveVisitor {
visitObject(type) {
console.log(`Object of type: ${type} requires role: ${this.args.requires}`)
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
// the parent and grandparent types.
visitFieldDefinition(field, details) {
console.log(`field: ${JSON.stringify(field)}, details: ${JSON.stringify(details)}`)
this.ensureFieldsWrapped(details.objectType);
field._requiredAuthRole = this.args.requires;
}
ensureFieldsWrapped(objectType) {
// Mark the GraphQLObjectType object to avoid re-wrapping:
console.log('ensureFieldsWrapped() called on objectType:', objectType)
if (objectType._authFieldsWrapped) return;
objectType._authFieldsWrapped = true;
const fields = objectType.getFields();
Object.keys(fields).forEach(fieldName => {
console.log(`Called on field ${fieldName}`)
const field = fields[fieldName];
const { resolve = defaultFieldResolver } = field;
field.resolve = async function (...args) {
const { user } = args[2];
console.log('Field.resolve called with args: ', JSON.stringify(...args));
console.log('Field.resolve called by user: ', JSON.stringify(user));
// Only return data if the isPublic field is true
if(user || args[0]['isPublic']) return resolve.apply(this, args);
};
});
}
}
module.exports = { AuthDirective };