Created
May 26, 2025 11:26
-
-
Save brunocarvalhodearaujo/732c6d4bd9dc36f03a1441c9ee57f48b to your computer and use it in GitHub Desktop.
apollo graphql upper directive
This file contains hidden or 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
/** | |
* 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