Skip to content

Instantly share code, notes, and snippets.

@pedropalhari
Last active January 28, 2022 18:10
Show Gist options
  • Save pedropalhari/fb718215ce8f538c8e4c0c31b86d7420 to your computer and use it in GitHub Desktop.
Save pedropalhari/fb718215ce8f538c8e4c0c31b86d7420 to your computer and use it in GitHub Desktop.
Nexus GraphQL `commonType` utility. To define fields to be shared.
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,
};
@pedropalhari
Copy link
Author

pedropalhari commented Oct 6, 2021

Example code to be used:

const UserCommonFields = NexusUtils.commonType((t) => {
  t.nonNull.string("name");
  t.nonNull.int("age");
});

const UserType = objectType({
  name: "UserType",
  definition(t) {
    UserCommonFields(t);

    t.nonNull.string("id");
  },
});

const UserInputType = inputObjectType({
  name: "UserInputType",
  definition(t) {
    UserCommonFields(t);
  },
});

const UserMutation = extendType({
  type: "Mutation",
  definition(t) {
    t.field("addUser", {
      type: UserType,
      args: {
        user: nonNull(UserInputType),
      },

      resolve: (_, args, ctx) => {
        const { user } = args;
        const id = (Math.random() * 10 ** 10).toFixed(0);

        const newUser = {
          id,
          ...user,
        };

        ctx.users.push(newUser);

        return newUser;
      },
    });
  },
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment