Skip to content

Commit

Permalink
Only emit ternary if there are no args
Browse files Browse the repository at this point in the history
  • Loading branch information
captbaritone committed Jan 19, 2024
1 parent ef40f6a commit 7f3266e
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 13 deletions.
32 changes: 19 additions & 13 deletions src/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,30 +262,36 @@ class Codegen {
F.createIdentifier("source"),
F.createIdentifier(name),
);
const callExpression = F.createCallExpression(
let valueExpression: ts.Expression = F.createCallExpression(
prop,
undefined,
RESOLVER_ARGS.map((name) => {
return F.createIdentifier(name);
}),
);

const isFunc = F.createStrictEquality(
F.createTypeOfExpression(prop),
F.createStringLiteral("function"),
);
// If there are no args, this might be a property not a method. In that case, we first need to
// check if the property is a function. If it is, we call it, otherwise we just read the prop.
if (field.args.length === 0) {
const isFunc = F.createStrictEquality(
F.createTypeOfExpression(prop),
F.createStringLiteral("function"),
);

const ternary = F.createConditionalExpression(
isFunc,
undefined,
valueExpression,
undefined,
prop,
);
valueExpression = ternary;
}

const ternary = F.createConditionalExpression(
isFunc,
undefined,
callExpression,
undefined,
prop,
);
return this.method(
methodName,
RESOLVER_ARGS.map((name) => this.param(name)),
[F.createReturnStatement(ternary)],
[F.createReturnStatement(valueExpression)],
);
}

Expand Down
7 changes: 7 additions & 0 deletions src/tests/fixtures/field_definitions/RenamedFieldWithArgs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/** @gqlType */
export default class SomeType {
/** @gqlField greetz */
hello(args: { greeting: string }): string {
return `${args.greeting} world!`;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
-----------------
INPUT
-----------------
/** @gqlType */
export default class SomeType {
/** @gqlField greetz */
hello(args: { greeting: string }): string {
return `${args.greeting} world!`;
}
}

-----------------
OUTPUT
-----------------
-- SDL --
type SomeType {
greetz(greeting: String!): String @propertyName(name: "hello")
}
-- TypeScript --
import { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLNonNull } from "graphql";
export function getSchema(): GraphQLSchema {
const SomeTypeType: GraphQLObjectType = new GraphQLObjectType({
name: "SomeType",
fields() {
return {
greetz: {
name: "greetz",
type: GraphQLString,
args: {
greeting: {
name: "greeting",
type: new GraphQLNonNull(GraphQLString)
}
},
resolve(source, args, context, info) {
return source.hello(source, args, context, info);
}
}
};
}
});
return new GraphQLSchema({
types: [SomeTypeType]
});
}

0 comments on commit 7f3266e

Please sign in to comment.