-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
44 lines (36 loc) · 1.12 KB
/
index.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
const {
DirectiveLocation,
GraphQLDirective,
GraphQLString,
defaultFieldResolver,
} = require('graphql');
const { SchemaDirectiveVisitor } = require('graphql-tools');
class computedDirective extends SchemaDirectiveVisitor {
static getDirectiveDeclaration(directiveName = 'rest') {
return new GraphQLDirective({
name: directiveName,
locations: [DirectiveLocation.FIELD_DEFINITION],
args: {
value: { type: GraphQLString },
},
});
}
visitFieldDefinition(field) {
const { resolve = defaultFieldResolver, name } = field;
field.resolve = async (root, args, context, info) => {
const result = await resolve.call(this, root, args, context, info);
const updatedRoot = Object.assign(root, { [name]: result });
let value = this.args.value;
for (const property in updatedRoot) {
if (Object.prototype.hasOwnProperty.call(updatedRoot, property)) {
value = value.replace(
new RegExp(`\\$${property}`, 'g'),
updatedRoot[property]
);
}
}
return value;
};
}
}
module.exports = computedDirective;