Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Plugin example: setting the GraphQL type to use for a given PostgreSQL type #270

Open
benjie opened this issue Apr 12, 2021 · 0 comments
Open

Comments

@benjie
Copy link
Member

benjie commented Apr 12, 2021

Thanks to @Gomes on Discord. This only works for scalar-like types, for composite types you'll need to register separate input and output types (i.e. in addition to calling pgRegisterGqlTypeByTypeId you also need to call pgRegisterGqlInputTypeByTypeId)

import type { GraphQLType } from "graphql";
import type { Plugin } from "graphile-build";
import type { PgType } from "graphile-build-pg";

interface PgDomainToGqlTypePluginArgs {
  /** PostgreSQL type identifier, e.g. "my_schema.my_type" */
  typeIdentifier: string;
  /** What GraphQL type should we use for this PG type */
  gqlType: GraphQLType | ((build: Build) => GraphQLType);
}

/**
 * Sets the GraphQL type `gqlType` to be used for the PostgreSQL type identified
 * by `typeIdentifier`
 */
export function makePgDomainToGqlTypePlugin({
  typeIdentifier,
  gqlType,
}: PgDomainToGqlTypePluginArgs): Plugin {
  return (builder) => {
    builder.hook("build", (build) => {
      const { namespaceName, entityName: typeName } = build.pgParseIdentifier(
        typeIdentifier
      );

      const pgType = build.pgIntrospectionResultsByKind.type.find(
        (type: PgType) =>
          type.namespaceName === namespaceName && type.name === typeName
      );

      if (!pgType) {
        throw new Error(`Failed to find the type '${typeIdentifier}'`);
      }

      build.pgRegisterGqlTypeByTypeId(pgType.id, () =>
        typeof gqlType === "function" ? gqlType(build) : gqlType
      );

      return build;
    });
  };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant