Skip to content

Instantly share code, notes, and snippets.

@brunocarvalhodearaujo
Created May 26, 2025 11:26
Show Gist options
  • Save brunocarvalhodearaujo/732c6d4bd9dc36f03a1441c9ee57f48b to your computer and use it in GitHub Desktop.
Save brunocarvalhodearaujo/732c6d4bd9dc36f03a1441c9ee57f48b to your computer and use it in GitHub Desktop.
apollo graphql upper directive
/**
* Copyright (c) 2023-present, Bruno Carvalho de Araujo.
* All rights reserved.
*
* This source code is licensed under the license found in the LICENSE file in
* the root directory of this source tree.
*/
import { getDirective, MapperKind, mapSchema } from '@graphql-tools/utils'
import { defaultFieldResolver, type DocumentNode, type GraphQLSchema } from 'graphql'
import gql from 'graphql-tag'
type DirectiveReturn = {
transformSchema: (schema: GraphQLSchema) => GraphQLSchema,
typeDefs: DocumentNode
}
export function upperDirective (directiveName: string = 'upper'): DirectiveReturn {
return {
typeDefs: gql`
directive @${directiveName} on FIELD_DEFINITION
`,
transformSchema: schema => mapSchema(schema, {
[MapperKind.OBJECT_FIELD]: fieldConfig => {
const upperDirective = getDirective(schema, fieldConfig, directiveName)?.[0]
if (!upperDirective) {
return undefined
}
const { resolve = defaultFieldResolver } = fieldConfig
return {
...fieldConfig,
resolve: async (source, args, context, info) => {
const result = await resolve(source, args, context, info)
if (typeof result === 'string') {
return result.toUpperCase()
}
return result
}
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment