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

Use primary key fields if available for the @key directive #2

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ const AddKeyPlugin: Plugin = builder => {
const {
GraphQLObjectType: spec,
Self,
scope: { isRootQuery },
scope: { isRootQuery, pgIntrospection },
} = context;
const NodeInterface = getTypeByName(inflection.builtin("Node"));

Expand All @@ -169,7 +169,8 @@ const AddKeyPlugin: Plugin = builder => {
build.federationEntityTypes.push(Self);

/*
* We're going to add the `@key(fields: "nodeId")` directive to this type.
* We're going to add the key directive to this type. If this type has a
* defined primary key we will use that, otherwise `@key(fields: "nodeId")`
* First, we need to generate an `astNode` as if the type was generateted
* from a GraphQL SDL initially; then we assign this astNode to to the type
* (via type mutation, ick) so that Apollo Federation's `printSchema` can
Expand All @@ -179,8 +180,17 @@ const AddKeyPlugin: Plugin = builder => {
...ObjectTypeDefinition(spec),
...Self.astNode,
};

const {
primaryKeyConstraint: { keyAttributes }
} = pgIntrospection;
const primaryKeyNames = keyAttributes.map(attr => inflection.column(attr));
const keyName = primaryKeyNames.length
? primaryKeyNames.join(' ')
: nodeIdFieldName;

astNode.directives.push(
Directive("key", { fields: StringValue(nodeIdFieldName) })
Directive("key", { fields: StringValue(keyName) })
);
Self.astNode = astNode;

Expand Down