diff --git a/src/classes/GraphQLQueryTree.ts b/src/classes/GraphQLQueryTree.ts index bb06c51..8d1befc 100644 --- a/src/classes/GraphQLQueryTree.ts +++ b/src/classes/GraphQLQueryTree.ts @@ -1,5 +1,6 @@ import {GraphQLResolveInfo} from "graphql"; import {buildQueryTree, GraphQLQueryTreeProperties} from "../"; +import {EntityMetadata} from "typeorm"; /** @@ -50,10 +51,10 @@ export class GraphQLQueryTree { } /** - * @description Check if this field is a relation + * @description Check if this field is a relation in metadata */ - public isRelation(): boolean { - return !!(this.fields && this.fields.length); + public isRelationIn(metadata: EntityMetadata): boolean { + return !!metadata.ownRelations.find((relation) => relation.propertyName === this.name); } /** diff --git a/src/functions/build-query-recursively.ts b/src/functions/build-query-recursively.ts index 019b5d2..0b13782 100644 --- a/src/functions/build-query-recursively.ts +++ b/src/functions/build-query-recursively.ts @@ -1,6 +1,7 @@ import {GraphQLQueryTree, PAGINATE} from "../"; import {RelationMetadata} from "typeorm/metadata/RelationMetadata"; import {EntityMetadata, SelectQueryBuilder} from "typeorm"; +import {ColumnMetadata} from "typeorm/metadata/ColumnMetadata"; /** * @description Builds a TypeORM query with the queryBuilder recursively, joining every requested relation, @@ -20,7 +21,7 @@ export function buildQueryRecursively( // Firstly, we list all selected fields at this level of the query tree const selectedFields = tree.fields - .filter((field: GraphQLQueryTree) => !field.isRelation()) + .filter((field: GraphQLQueryTree) => !field.isRelationIn(metadata)) .map((field: GraphQLQueryTree) => alias + "." + field.name); // Secondly, we list all fields used in arguments @@ -28,9 +29,14 @@ export function buildQueryRecursively( .keys(tree.properties.args) .map((arg: string) => alias + "." + arg); + // Thirdly, we select all primary keys, to make sure that joined relations are not null + const primaryFields = metadata.primaryColumns + .map((ref: ColumnMetadata) => alias + "." + ref.propertyPath) + // We select all of above qb.addSelect(argFields); qb.addSelect(selectedFields); + qb.addSelect(primaryFields) // We add order options Object.keys(options.order) @@ -58,7 +64,7 @@ export function buildQueryRecursively( // For each asked relation tree.fields - .filter((field: GraphQLQueryTree) => field.isRelation()) + .filter((field: GraphQLQueryTree) => field.isRelationIn(metadata)) .forEach((relationTree: GraphQLQueryTree) => { const relation: RelationMetadata = metadata.findRelationWithPropertyPath(relationTree.name);