Skip to content

Commit e52a867

Browse files
committed
fix directive and update sample
1 parent fd6b898 commit e52a867

File tree

4 files changed

+36
-3
lines changed

4 files changed

+36
-3
lines changed

examples/federation/reviews-service/index.js

+4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const GraphQLComponent = require('../../../lib');
55
const ReviewsDataSource = require('./datasource');
66
const resolvers = require('./resolvers');
77
const types = require('./types');
8+
const toUppercaseDirective = require('./toUppercaseDirective')
89

910
class ReviewsComponent extends GraphQLComponent {
1011
constructor(options) {
@@ -17,6 +18,9 @@ const run = async function () {
1718
types,
1819
resolvers,
1920
dataSources: [new ReviewsDataSource()],
21+
directives: {
22+
toUppercase: toUppercaseDirective
23+
},
2024
federation: true
2125
});
2226

examples/federation/reviews-service/schema.graphql

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
directive @toUppercase on FIELD_DEFINITION
2+
13
type Review {
24
id: ID!
3-
content: String!
5+
content: String! @toUppercase
46
}
57

68
extend type Property @key(fields: "id") {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const {getDirective, MapperKind, mapSchema} = require("@graphql-tools/utils");
2+
const {defaultFieldResolver} = require("graphql");
3+
4+
function toUppercaseDirective(directiveName) {
5+
return (schema) => mapSchema(schema, {
6+
[MapperKind.OBJECT_FIELD]: (fieldConfig) => {
7+
const upperDirective = getDirective(schema, fieldConfig, directiveName)?.[0];
8+
if (upperDirective) {
9+
const {resolve = defaultFieldResolver} = fieldConfig;
10+
return {
11+
...fieldConfig,
12+
resolve: async function (source, args, context, info) {
13+
const result = await resolve(source, args, context, info);
14+
if (typeof result === 'string') {
15+
return result.toUpperCase();
16+
}
17+
return result;
18+
}
19+
}
20+
}
21+
}
22+
})
23+
}
24+
25+
module.exports = toUppercaseDirective

lib/index.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -102,11 +102,13 @@ class GraphQLComponent {
102102
_getMakeSchemaFunction() {
103103
if (this._federation) {
104104
return (schemaConfig) => {
105-
const schema = buildFederatedSchema(schemaConfig);
105+
let schema = buildFederatedSchema(schemaConfig);
106106

107107
// allows a federated schema to have custom directives using the old class based directive implementation
108108
if (this._directives) {
109-
SchemaDirectiveVisitor.visitSchemaDirectives(schema, this._directives);
109+
for (const name in this._directives) {
110+
schema = this._directives[name](name)(schema)
111+
}
110112
}
111113

112114
return schema;

0 commit comments

Comments
 (0)