Skip to content
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
27 changes: 27 additions & 0 deletions packages/graphql/src/graphql/directives/group-by.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { DirectiveLocation, GraphQLDirective } from "graphql";

export const groupByDirective = new GraphQLDirective({
name: "groupBy",
description: "Enables groupBy operations for this field",
locations: [DirectiveLocation.FIELD_DEFINITION],
args: {},
});
1 change: 1 addition & 0 deletions packages/graphql/src/graphql/directives/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export { declareRelationshipDirective } from "./declare-relationship";
export { defaultDirective } from "./default";
export { filterableDirective } from "./filterable";
export { fulltextDirective } from "./fulltext";
export { groupByDirective } from "./group-by";
export { idDirective } from "./id";
export { jwtClaim } from "./jwt-claim";
export { jwt } from "./jwt-payload";
Expand Down
4 changes: 4 additions & 0 deletions packages/graphql/src/schema-model/annotation/Annotation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { parseCypherAnnotation } from "../parser/annotations-parser/cypher-annot
import { parseDefaultAnnotation } from "../parser/annotations-parser/default-annotation";
import { parseFilterableAnnotation } from "../parser/annotations-parser/filterable-annotation";
import { parseFulltextAnnotation } from "../parser/annotations-parser/full-text-annotation";
import { parseGroupByAnnotation } from "../parser/annotations-parser/group-by-annotation";
import { parseJWTClaimAnnotation } from "../parser/annotations-parser/jwt-claim-annotation";
import { parseKeyAnnotation } from "../parser/annotations-parser/key-annotation";
import { parseLimitAnnotation } from "../parser/annotations-parser/limit-annotation";
Expand All @@ -48,6 +49,7 @@ import type { CypherAnnotation } from "./CypherAnnotation";
import type { DefaultAnnotation } from "./DefaultAnnotation";
import type { FilterableAnnotation } from "./FilterableAnnotation";
import type { FulltextAnnotation } from "./FulltextAnnotation";
import type { GroupByAnnotation } from "./GroupByAnnotation";
import { IDAnnotation } from "./IDAnnotation";
import type { JWTClaimAnnotation } from "./JWTClaimAnnotation";
import { JWTPayloadAnnotation } from "./JWTPayloadAnnotation";
Expand Down Expand Up @@ -98,6 +100,7 @@ export type Annotations = CheckAnnotationName<{
query: QueryAnnotation;
relayId: RelayIDAnnotation;
selectable: SelectableAnnotation;
groupBy: GroupByAnnotation;
settable: SettableAnnotation;
sortable: SortableAnnotation;
subscription: SubscriptionAnnotation;
Expand Down Expand Up @@ -132,6 +135,7 @@ export const annotationsParsers: { [key in keyof Annotations]: AnnotationParser<
selectable: parseSelectableAnnotation,
settable: parseSettableAnnotation,
sortable: parseSortableAnnotation,
groupBy: parseGroupByAnnotation,
subscription: parseSubscriptionAnnotation,
subscriptionsAuthorization: parseSubscriptionsAuthorizationAnnotation,
timestamp: parseTimestampAnnotation,
Expand Down
24 changes: 24 additions & 0 deletions packages/graphql/src/schema-model/annotation/GroupByAnnotation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { Annotation } from "./Annotation";

export class GroupByAnnotation implements Annotation {
readonly name = "groupBy";
}
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,10 @@ export class AttributeAdapter {
);
}

canGroupBy(): boolean {
return Boolean(this.annotations.groupBy);
}

isAggregationWhereField(): boolean {
if (
this.typeHelper.isList() ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,10 @@ export class ConcreteEntityAdapter {
return Array.from(this.attributes.values()).filter((attribute) => attribute.isAggregableField());
}

public get groupByFields(): AttributeAdapter[] {
return Array.from(this.attributes.values()).filter((attribute) => attribute.canGroupBy());
}

public get aggregationWhereFields(): AttributeAdapter[] {
return Array.from(this.attributes.values()).filter((attribute) => attribute.isAggregationWhereField());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ export class ConcreteEntityOperations extends ImplementingEntityOperations<Concr
return `${this.entityAdapter.name}Edge`;
}

public getConnectionGroupByInputTypename(): string {
return `${this.entityAdapter.name}GroupByInput`;
}

public getConnectionGroupByTypename(): string {
return `${this.entityAdapter.name}GroupBy`;
}

public getConnectionGroupByEdgeTypename(): string {
return `${this.entityAdapter.name}GroupByEdge`;
}

public get rootTypeFieldNames(): RootTypeFieldNames {
return {
...super.rootTypeFieldNames,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { DirectiveNode } from "graphql";
import { GroupByAnnotation } from "../../annotation/GroupByAnnotation";

export function parseGroupByAnnotation(_directive: DirectiveNode): GroupByAnnotation {
return new GroupByAnnotation();
}
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,13 @@ export abstract class RelationshipBaseOperations<T extends RelationshipAdapter |
return `${this.prefixForTypenameWithInheritance}${ifUnionRelationshipTargetEntity?.name || ""}ConnectionWhere`;
}

public getConnectionGroupByTypename(): string {
return `${this.prefixForTypenameWithInheritance}GroupBy`;
}
public getConnectionGroupByEdgeTypename(): string {
return `${this.prefixForTypenameWithInheritance}GroupByEdge`;
}

public getUpdateConnectionInputTypename(ifUnionRelationshipTargetEntity?: ConcreteEntityAdapter): string {
return `${this.prefixForTypename}${ifUnionRelationshipTargetEntity?.name || ""}UpdateConnectionInput`;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ export function augmentObjectOrInterfaceTypeWithConnectionField(
(directive) => directive.name.value === DEPRECATED
)
);

const composeNodeArgs: ObjectTypeComposerArgumentConfigMapDefinition = {};

// we want this type to be created for single relationships, but don't want to set the argument
Expand Down
123 changes: 123 additions & 0 deletions packages/graphql/src/schema/generation/connection-group-by.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type {
InputTypeComposer,
ObjectTypeComposer,
ObjectTypeComposerArgumentConfigMapDefinition,
SchemaComposer,
} from "graphql-compose";
import type { ConcreteEntityAdapter } from "../../schema-model/entity/model-adapters/ConcreteEntityAdapter";
import type { RelationshipAdapter } from "../../schema-model/relationship/model-adapters/RelationshipAdapter";

/** Returns the type and args for groupBy field in connections */
export function makeConnectionGroupByType({
entityAdapter,
composer,
}: {
entityAdapter: ConcreteEntityAdapter;
composer: SchemaComposer;
}): { type: ObjectTypeComposer; args: ObjectTypeComposerArgumentConfigMapDefinition } | undefined {
const typeName = entityAdapter.operations.getConnectionGroupByTypename();
const groupByFields = entityAdapter.groupByFields;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this seems unnecessary as it's only used once


if (groupByFields.length === 0) {
return undefined;
}

return getOrCreateConnectionGroupBy({
typeName,
composer,
edgeType: getGroupByEdgeType({ composer, entityAdapter }),
entityAdapter,
});
}

function getOrCreateConnectionGroupBy({
typeName,
composer,
edgeType,
entityAdapter,
}: {
typeName: string;
composer: SchemaComposer;
edgeType: ObjectTypeComposer;
entityAdapter: ConcreteEntityAdapter;
}): {
type: ObjectTypeComposer;
args: ObjectTypeComposerArgumentConfigMapDefinition;
} {
const inputArgs = getInputArgs({ entityAdapter, composer });

if (composer.has(typeName)) {
return { type: composer.getOTC(typeName), args: inputArgs };
}

const connectionGroupByOTC = composer.createObjectTC(typeName);
connectionGroupByOTC.addFields({
edges: edgeType.NonNull.List.NonNull,
});

return { type: connectionGroupByOTC, args: inputArgs };
}

function getGroupByEdgeType({
entityAdapter,
composer,
}: {
entityAdapter: ConcreteEntityAdapter | RelationshipAdapter;
composer: SchemaComposer;
}): ObjectTypeComposer {
const edgeTypeName = entityAdapter.operations.getConnectionGroupByEdgeTypename();
return composer.getOrCreateOTC(edgeTypeName, (oc) => {
const nodeType = composer.getOTC(entityAdapter.name);
oc.addFields({
node: nodeType.NonNull,
});
});
}

function getInputArgs({ entityAdapter, composer }: { entityAdapter: ConcreteEntityAdapter; composer: SchemaComposer }) {
const inputType = getOrCreateConnectionGroupByInputType({ entityAdapter, composer });
return {
fields: inputType.NonNull,
};
}

function getOrCreateConnectionGroupByInputType({
entityAdapter,
composer,
}: {
entityAdapter: ConcreteEntityAdapter;
composer: SchemaComposer;
}): InputTypeComposer {
const typeName = entityAdapter.operations.getConnectionGroupByInputTypename();
if (composer.has(typeName)) {
return composer.getITC(typeName);
}

const connectionGroupByITC = composer.createInputTC(typeName);
for (const attribute of entityAdapter.groupByFields) {
connectionGroupByITC.addFields({
[attribute.name]: "Boolean",
});
}

return connectionGroupByITC;
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ export function withConnectionObjectType({
const connectionObjectType = composer.getOrCreateOTC(typeName);

if (relationshipAdapter.isReadable()) {
const edgeType = withRelationshipObjectType({ relationshipAdapter, composer });

connectionObjectType.addFields({
edges: withRelationshipObjectType({ relationshipAdapter, composer }).NonNull.List.NonNull,
edges: edgeType.NonNull.List.NonNull,
totalCount: new GraphQLNonNull(GraphQLInt),
pageInfo: new GraphQLNonNull(PageInfo),
});
Expand Down
3 changes: 3 additions & 0 deletions packages/graphql/src/schema/pagination.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ describe("cursor-pagination", () => {
expect(result).toStrictEqual({
aggregate: {},
edges: arraySlice.map((edge, index) => ({ ...edge, cursor: offsetToCursor(index) })),
groupBy: [],
pageInfo: {
hasNextPage: false,
hasPreviousPage: false,
Expand All @@ -71,6 +72,7 @@ describe("cursor-pagination", () => {
expect(result).toStrictEqual({
aggregate: {},
edges: arraySlice.map((edge, index) => ({ ...edge, cursor: offsetToCursor(index) })),
groupBy: [],
pageInfo: {
hasNextPage: false,
hasPreviousPage: false,
Expand All @@ -92,6 +94,7 @@ describe("cursor-pagination", () => {
expect(result).toStrictEqual({
aggregate: {},
edges: arraySlice.map((edge, index) => ({ ...edge, cursor: offsetToCursor(index + 11) })),
groupBy: [],
pageInfo: {
hasNextPage: false,
hasPreviousPage: true,
Expand Down
3 changes: 3 additions & 0 deletions packages/graphql/src/schema/pagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ export function createConnectionWithEdgeProperties({

const edges: any[] = source?.edges || [];
const aggregate: any = source?.aggregate || {};
const groupBy: any = source?.groupBy || [];

const selections = selectionSet?.selections || [];

Expand All @@ -116,6 +117,7 @@ export function createConnectionWithEdgeProperties({
const pageInfoKey = getAliasKey({ selectionSet, key: "pageInfo" });
const edgesKey = getAliasKey({ selectionSet, key: "edges" });
const aggregateKey = getAliasKey({ selectionSet, key: "aggregate" });
const groupByKey = getAliasKey({ selectionSet, key: "groupBy" });
const pageInfoField = selections.find((x): x is FieldNode => x.kind === Kind.FIELD && x.name.value === "pageInfo");
const pageInfoSelectionSet = pageInfoField?.selectionSet;
const startCursorKey = getAliasKey({ selectionSet: pageInfoSelectionSet, key: "startCursor" });
Expand All @@ -126,6 +128,7 @@ export function createConnectionWithEdgeProperties({
return {
[edgesKey]: mappedEdges,
[aggregateKey]: aggregate,
[groupByKey]: groupBy,
[pageInfoKey]: {
[startCursorKey]: startCursor,
[endCursorKey]: endCursor,
Expand Down
Loading
Loading