Last active
January 28, 2022 18:10
-
-
Save pedropalhari/fb718215ce8f538c8e4c0c31b86d7420 to your computer and use it in GitHub Desktop.
Nexus GraphQL `commonType` utility. To define fields to be shared.
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
import { InputDefinitionBlock, OutputDefinitionBlock } from "nexus/dist/blocks"; | |
type TType<T extends string> = | |
| InputDefinitionBlock<T> | |
| OutputDefinitionBlock<T>; | |
// Type for the definition. | |
type CommonTypeDefinitionFunction = <T extends string>( | |
t: InputDefinitionBlock<T> | |
) => void; | |
// Type to be used when passing `t` down to the definition | |
type CommonTypeReturnFunction = <T extends string>(t: TType<T>) => void; | |
/** | |
* Function to build a common type function, to be used accross | |
* multiple ObjectType and InputObjectType definitions | |
* @param commonTypeDefinition | |
* @returns | |
*/ | |
function commonType( | |
commonTypeDefinition: CommonTypeDefinitionFunction | |
): CommonTypeReturnFunction { | |
// Accept `t` from both objectType and inputObjectType | |
return <T extends string>(t: TType<T>) => | |
// But restrict it here as the input type, as it's a subset of the object one. | |
commonTypeDefinition(t as InputDefinitionBlock<T>); | |
} | |
export const NexusUtils = { | |
commonType, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example code to be used: