Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(#28): example with custom directive #35

Merged
merged 1 commit into from
Aug 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 })
Loading