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

try to use primary key as additional @key directive #3

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@
"typescript": "^3.4.4"
},
"peerDependencies": {
"graphile-build": "^4.4.2"
"graphile-build": "^4.4.2",
"graphile-build-pg": "^4.4.5"
},
"files": [
"build"
Expand Down
124 changes: 113 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
import { Plugin } from "graphile-build";
import printFederatedSchema from "./printFederatedSchema";
import { ObjectTypeDefinition, Directive, StringValue } from "./AST";
import { PgAttribute, QueryBuilder } from "graphile-build-pg";

/**
* This plugin installs the schema outlined in the Apollo Federation spec, and
Expand All @@ -22,8 +23,13 @@ const SchemaExtensionPlugin = makeExtendSchemaPlugin(build => {
$$isQuery,
$$nodeType,
getTypeByName,
scopeByType,
inflection,
nodeIdFieldName,
pgSql: sql,
parseResolveInfo,
pgQueryFromResolveData: queryFromResolveData,
pgPrepareAndRun,
} = build;
// Cache
let Query: any;
Expand Down Expand Up @@ -81,25 +87,83 @@ const SchemaExtensionPlugin = makeExtendSchemaPlugin(build => {
resolvers: {
Query: {
_entities(data, { representations }, context, resolveInfo) {
const { pgClient } = context;
const {
graphile: { fieldContext },
} = resolveInfo;
return representations.map((representation: any) => {
return representations.map(async (representation: any) => {
phryneas marked this conversation as resolved.
Show resolved Hide resolved
if (!representation || typeof representation !== "object") {
throw new Error("Invalid representation");
}

const { __typename, [nodeIdFieldName]: nodeId } = representation;
if (!__typename || typeof nodeId !== "string") {
throw new Error("Failed to interpret representation");
if (!__typename) {
throw new Error(
"Failed to interpret representation, no typename"
);
}
if (nodeId) {
if (typeof nodeId !== "string") {
throw new Error(
"Failed to interpret representation, invalid nodeId"
);
}
return resolveNode(
nodeId,
build,
fieldContext,
data,
context,
resolveInfo
);
} else {
const type = getTypeByName(__typename);
const { pgIntrospection: table } = scopeByType.get(type);

if (!table.primaryKeyConstraint) {
throw new Error("Failed to interpret representation");
}
const {
primaryKeyConstraint: { keyAttributes },
} = table;

const whereClause = sql.fragment`(${sql.join(
keyAttributes.map(
(attr: PgAttribute) =>
sql.fragment`${sql.identifier(attr.name)} = ${sql.value(
representation[inflection.column(attr)]
)}`
),
") and ("
)})`;

const resolveData = fieldContext.getDataFromParsedResolveInfoFragment(
parseResolveInfo(resolveInfo),
type
);

const query = queryFromResolveData(
sql.identifier(table.namespace.name, table.name),
undefined,
resolveData,
{
useAsterisk: false, // Because it's only a single relation, no need
},
(queryBuilder: QueryBuilder) => {
queryBuilder.where(whereClause);
},
context,
resolveInfo.rootValue
);

const { text, values } = sql.compile(query);

const {
rows: [row],
} = await pgPrepareAndRun(pgClient, text, values);

return { [$$nodeType]: __typename, ...row };
}
return resolveNode(
nodeId,
build,
fieldContext,
data,
context,
resolveInfo
);
});
},

Expand Down Expand Up @@ -147,6 +211,44 @@ const AddKeyPlugin: Plugin = builder => {
return build;
});

builder.hook("GraphQLObjectType", (type, build, context) => {
const {
scope: { pgIntrospection, isPgRowType },
} = context;

const { inflection } = build;

if (
!(
isPgRowType &&
pgIntrospection.isSelectable &&
pgIntrospection.namespace &&
pgIntrospection.primaryKeyConstraint
)
) {
return type;
}

const primaryKeyNames = pgIntrospection.primaryKeyConstraint.keyAttributes.map(
(attr: PgAttribute) => inflection.column(attr)
);

if (!primaryKeyNames.length) {
return type;
}

const astNode = {
...ObjectTypeDefinition({ name: type.name }),
...type.astNode,
};

(astNode.directives as any).push(
Directive("key", { fields: StringValue(primaryKeyNames.join(" ")) })
);

return { ...type, astNode } as typeof type;
});

// Find out what types implement the Node interface
builder.hook("GraphQLObjectType:interfaces", (interfaces, build, context) => {
const { getTypeByName, inflection, nodeIdFieldName } = build;
Expand Down