Skip to content

Commit

Permalink
refactor(graphql): add isValidMethodReturnType fn
Browse files Browse the repository at this point in the history
  • Loading branch information
marcus-sa committed Sep 20, 2023
1 parent f4e28ce commit 31bb7dd
Showing 1 changed file with 12 additions and 14 deletions.
26 changes: 12 additions & 14 deletions packages/graphql/src/lib/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ import { requireTypeName, unwrapPromiseLikeType } from './types-builder';

export const typeResolvers = new Map<string, ClassType>();

export function isValidMethodReturnType(classType: ClassType, methodName: string): boolean {
const resolverType = resolveRuntimeType(classType);
const reflectionClass = ReflectionClass.from(resolverType);
const method = reflectionClass.getMethod(methodName);
let returnType = method.getReturnType();
returnType = unwrapPromiseLikeType(returnType);

return returnType.kind === ReflectionKind.objectLiteral || returnType.kind === ReflectionKind.class;
}

class GraphQLResolver {
type?: TypeClass | TypeObjectLiteral;

Expand Down Expand Up @@ -122,13 +132,7 @@ class GraphQLQueryDecorator {
this.t.deprecationReason = options?.deprecationReason;

this.t.checks.add(() => {
const resolverType = resolveRuntimeType(this.t.classType);
const reflectionClass = ReflectionClass.from(resolverType);
const method = reflectionClass.getMethod(this.t.name);
let returnType = method.getReturnType();
returnType = unwrapPromiseLikeType(returnType);

if (returnType.kind !== ReflectionKind.objectLiteral && returnType.kind !== ReflectionKind.class) {
if (!isValidMethodReturnType(this.t.classType, this.t.name)) {
throw new Error(
'Only classes and interfaces are supported as return types for methods decorated by @graphql.query()',
);
Expand Down Expand Up @@ -174,13 +178,7 @@ class GraphQLMutationDecorator {
this.t.deprecationReason = options?.deprecationReason;

this.t.checks.add(() => {
const resolverType = resolveRuntimeType(this.t.classType);
const reflectionClass = ReflectionClass.from(resolverType);
const method = reflectionClass.getMethod(this.t.name);
let returnType = method.getReturnType();
returnType = unwrapPromiseLikeType(returnType);

if (returnType.kind !== ReflectionKind.objectLiteral && returnType.kind !== ReflectionKind.class) {
if (!isValidMethodReturnType(this.t.classType, this.t.name)) {
throw new Error(
'Only classes and interfaces are supported as return types for methods decorated by @graphql.mutation()',
);
Expand Down

0 comments on commit 31bb7dd

Please sign in to comment.