Skip to content

Commit

Permalink
fix(graphql,federation,#1051): return null for references
Browse files Browse the repository at this point in the history
  • Loading branch information
mwoelk authored and doug-martin committed Apr 13, 2021
1 parent 55cb010 commit 6cb832e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
4 changes: 2 additions & 2 deletions packages/query-graphql/src/decorators/reference.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ import { BaseResolverOptions } from './resolver-method.decorator';
import { mergeBaseResolverOpts } from '../common';

const reflector = new ArrayReflector(REFERENCE_KEY);
export type ReferenceDecoratorOpts<DTO, Relation> = Omit<ResolverRelationReference<DTO, Relation>, 'DTO'>;
export type ReferenceDecoratorOpts<DTO, Relation> = Omit<ResolverRelationReference<DTO, Relation>, 'DTO' | 'keys'>;
export type ReferenceTypeFunc<Relation> = () => Class<Relation>;

interface ReferenceDescriptor<DTO, Reference> {
name: string;
keys: ReferencesKeys<DTO, Reference>;
relationTypeFunc: () => Class<Reference>;
relationOpts?: Omit<ResolverRelationReference<DTO, Reference>, 'DTO'>;
relationOpts?: Omit<ResolverRelationReference<DTO, Reference>, 'DTO' | 'keys'>;
}

function getReferenceDescriptors<DTO>(DTOClass: Class<DTO>): ReferenceDescriptor<DTO, unknown>[] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ const pluckFields = <DTO, Relation>(dto: DTO, fieldMap: ReferencesKeys<DTO, Rela
return partial as Partial<Relation>;
};

const allFieldsAreNull = <Relation>(fields: Partial<Relation>): boolean => {
return Object.entries(fields).reduce<boolean>((previousNull, [, value]) => previousNull && value === null, true);
};

const ReferencesMixin = <DTO, Relation>(DTOClass: Class<DTO>, reference: ResolverRelationReference<DTO, Relation>) => <
B extends Class<ServiceResolver<DTO, QueryService<DTO, unknown, unknown>>>
>(
Expand All @@ -33,9 +37,15 @@ const ReferencesMixin = <DTO, Relation>(DTOClass: Class<DTO>, reference: Resolve
{ nullable: reference.nullable, complexity: reference.complexity },
commonResolverOpts,
)
[`${baseNameLower}Reference`](@Parent() dto: DTO): RepresentationType {
[`${baseNameLower}Reference`](@Parent() dto: DTO): RepresentationType | null {
const fields = pluckFields<DTO, Relation>(dto, reference.keys);

if (allFieldsAreNull(fields)) {
return null;
}

// eslint-disable-next-line @typescript-eslint/naming-convention
return { __typename: baseName, ...pluckFields<DTO, Relation>(dto, reference.keys) };
return { __typename: baseName, ...fields };
}
}
return ReadOneMixin;
Expand Down

0 comments on commit 6cb832e

Please sign in to comment.