-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
- Loading branch information
Showing
1 changed file
with
83 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }) |