Skip to content

Commit

Permalink
docs(mercurius-js#28): example with custom directive
Browse files Browse the repository at this point in the history
  • Loading branch information
Puppo committed Aug 11, 2023
1 parent 6c5a751 commit f3cac9a
Showing 1 changed file with 83 additions and 0 deletions.
83 changes: 83 additions & 0 deletions examples/withCustomDirectives.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
'use strict'

const Fastify = require('fastify')
const { mapSchema, getDirective, MapperKind, printSchemaWithDirectives, getResolversFromSchema } = require('@graphql-tools/utils')
const { mergeResolvers } = require('@graphql-tools/merge')
const { makeExecutableSchema } = require('@graphql-tools/schema')
const mercurius = require('mercurius')
const { buildFederationSchema } = require('../')

const users = {
1: {
id: '1',
name: 'John',
username: '@john'
},
2: {
id: '2',
name: 'Jane',
username: '@jane'
}
}

const upperCaseDirectiveTypeDefs = 'directive @upper on FIELD_DEFINITION'
const uppercaseTransformer = (schema) =>
mapSchema(schema, {
[MapperKind.FIELD]: (fieldConfig) => {
const upperDirective = getDirective(schema, fieldConfig, 'upper')?.[0]
if (upperDirective) {
fieldConfig.resolve = async (obj, _args, _ctx, info) => {
const value = obj[info.fieldName]
return typeof value === 'string' ? value.toUpperCase() : value
}
}
}
})

const app = Fastify()
const schema = `
${upperCaseDirectiveTypeDefs}
extend type Query {
me: User
}
type User @key(fields: "id") {
id: ID!
name: String @upper
username: String
}
`

const resolvers = {
Query: {
me: () => {
return users['1']
}
},
User: {
__resolveReference: source => {
return users[source.id]
}
}
}

const federationSchema = buildFederationSchema(schema)

const executableSchema = makeExecutableSchema({
typeDefs: printSchemaWithDirectives(federationSchema),
resolvers: mergeResolvers([getResolversFromSchema(federationSchema), resolvers])
})

app.register(mercurius, {
schema: executableSchema,
schemaTransforms: [uppercaseTransformer],
graphiql: true
})

app.get('/', async function () {
const query = '{ _service { sdl } }'
return app.graphql(query)
})

app.listen({ port: 3000 })

0 comments on commit f3cac9a

Please sign in to comment.