Skip to content

feat: support custom directives #134

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 23, 2025
Merged
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
28 changes: 22 additions & 6 deletions src/annotations/build-directive-annotations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { ConstDirectiveNode } from "graphql/language";
import { GraphQLSchema, isInputObjectType, Kind } from "graphql";
import { shouldConsolidateTypes } from "../utils/should-consolidate-types";
import { sanitizeName } from "../utils/sanitize-name";
import { titleCase } from "../utils/title-case";

export function buildDirectiveAnnotations(
definitionNode: DefinitionNode,
Expand Down Expand Up @@ -50,17 +51,32 @@ export function buildDirectiveAnnotations(
return !typeWillBeConsolidated;
},
);
if (!directiveReplacementFromConfig) return "";
const kotlinAnnotations = buildKotlinAnnotations(
directive,
directiveReplacementFromConfig.kotlinAnnotations,

if (directiveReplacementFromConfig) {
return (
buildKotlinAnnotationsFromConfig(
directive,
directiveReplacementFromConfig.kotlinAnnotations,
).join("\n") + "\n"
);
}
const customDirectiveFromConfig = config.customDirectives?.find(
(directive) => directive === directiveName,
);
return kotlinAnnotations.join("\n") + "\n";
if (customDirectiveFromConfig) {
return buildCustomDirective(directive);
}
return "";
})
.join("");
}

function buildKotlinAnnotations(
function buildCustomDirective(directive: ConstDirectiveNode) {
const directiveName = directive.name.value;
return `@${titleCase(directiveName)}\n`;
}

function buildKotlinAnnotationsFromConfig(
directive: ConstDirectiveNode,
kotlinAnnotations: NonNullable<
CodegenConfigWithDefaults["directiveReplacements"]
Expand Down
10 changes: 10 additions & 0 deletions src/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@ export const configSchema = object({
* @link https://opensource.expediagroup.com/graphql-kotlin-codegen/docs/class-consolidation
*/
classConsolidationEnabled: optional(boolean()),
/**
* Denotes directives to generate as @GraphQLDirective annotations.
*
* Directive arguments are not yet supported and will be ignored.
*
* @example ["myCustomDirective"]
*
* @link https://opensource.expediagroup.com/graphql-kotlin/docs/schema-generator/customizing-schemas/directives/#custom-directives
*/
customDirectives: optional(array(string())),
/**
* Limits dependent types to include from `onlyTypes` list. Can be used to exclude classes that are imported from external packages.
*
Expand Down
33 changes: 33 additions & 0 deletions src/definitions/directive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
Copyright 2024 Expedia, Inc.
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
https://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 { DirectiveDefinitionNode } from "graphql";
import { CodegenConfigWithDefaults } from "../config/build-config-with-defaults";
import { titleCase } from "../utils/title-case";

export function buildDirectiveDefinition(
node: DirectiveDefinitionNode,
config: CodegenConfigWithDefaults,
): string {
const directiveName = node.name.value;
const isCustomDirective = config.customDirectives?.includes(directiveName);
if (!isCustomDirective) {
return "";
}
return `@GraphQLDirective(
name = "${titleCase(directiveName)}",
description = "${node.description?.value ?? ""}",
locations = [${node.locations.map((location) => `graphql.introspection.Introspection.DirectiveLocation.${location.value}`).join(", ")}]

Choose a reason for hiding this comment

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

it doesn't really matter all that much, but why inline the imports?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Just easier than manually adding the imports to the top of the file which would require adding them to the extraImports config

)
annotation class ${titleCase(directiveName)}`;
}
6 changes: 6 additions & 0 deletions src/visitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ limitations under the License.

import { BaseVisitor, RawConfig } from "@graphql-codegen/visitor-plugin-common";
import {
DirectiveDefinitionNode,
EnumTypeDefinitionNode,
GraphQLSchema,
InputObjectTypeDefinitionNode,
Expand All @@ -21,6 +22,7 @@ import {
UnionTypeDefinitionNode,
} from "graphql";
import { CodegenConfigWithDefaults } from "./config/build-config-with-defaults";
import { buildDirectiveDefinition } from "./definitions/directive";
import { buildEnumTypeDefinition } from "./definitions/enum";
import { buildInterfaceDefinition } from "./definitions/interface";
import { buildInputObjectDefinition } from "./definitions/input";
Expand All @@ -39,6 +41,10 @@ export class KotlinVisitor extends BaseVisitor<
super(rawConfig, rawConfig);
}

DirectiveDefinition(node: DirectiveDefinitionNode): string {
return buildDirectiveDefinition(node, this.config);
}

EnumTypeDefinition(node: EnumTypeDefinitionNode): string {
return buildEnumTypeDefinition(node, this._schema, this.config);
}
Expand Down
12 changes: 12 additions & 0 deletions test/unit/should_generate_custom_directives/codegen.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { GraphQLKotlinCodegenConfig } from "../../../src/plugin";

export default {
customDirectives: ["myCustomDirective", "myCustomDirective2"],
extraImports: ["should_honor_directiveReplacements_config.*"],
directiveReplacements: [
{
directive: "someDirective1",
kotlinAnnotations: ["@SomeAnnotation1"],
},
],
} satisfies GraphQLKotlinCodegenConfig;
44 changes: 44 additions & 0 deletions test/unit/should_generate_custom_directives/expected.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.kotlin.generated

import com.expediagroup.graphql.generator.annotations.*
import should_honor_directiveReplacements_config.*

@GraphQLDirective(
name = "MyCustomDirective",
description = "A description for MyCustomDirective",
locations = [graphql.introspection.Introspection.DirectiveLocation.OBJECT, graphql.introspection.Introspection.DirectiveLocation.FIELD_DEFINITION, graphql.introspection.Introspection.DirectiveLocation.INPUT_OBJECT, graphql.introspection.Introspection.DirectiveLocation.INPUT_FIELD_DEFINITION]
)
annotation class MyCustomDirective

@GraphQLDirective(
name = "MyCustomDirective2",
description = "",
locations = [graphql.introspection.Introspection.DirectiveLocation.OBJECT, graphql.introspection.Introspection.DirectiveLocation.FIELD_DEFINITION, graphql.introspection.Introspection.DirectiveLocation.INPUT_OBJECT, graphql.introspection.Introspection.DirectiveLocation.INPUT_FIELD_DEFINITION]
)
annotation class MyCustomDirective2

@MyCustomDirective
@MyCustomDirective2
@SomeAnnotation1
@GraphQLValidObjectLocations(locations = [GraphQLValidObjectLocations.Locations.OBJECT])
data class MyTypeWithCustomDirectiveOnObject(
val field: String? = null
)

@GraphQLValidObjectLocations(locations = [GraphQLValidObjectLocations.Locations.OBJECT])
data class MyTypeWithCustomDirectiveOnField(
@MyCustomDirective
val field: String? = null
)

@MyCustomDirective
@GraphQLValidObjectLocations(locations = [GraphQLValidObjectLocations.Locations.INPUT_OBJECT])
data class MyInputWithCustomDirectiveOnObject(
val field: String? = null
)

@GraphQLValidObjectLocations(locations = [GraphQLValidObjectLocations.Locations.INPUT_OBJECT])
data class MyInputWithCustomDirectiveOnField(
@MyCustomDirective
val field: String? = null
)
24 changes: 24 additions & 0 deletions test/unit/should_generate_custom_directives/schema.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"A description for MyCustomDirective"
directive @myCustomDirective on OBJECT | FIELD_DEFINITION | INPUT_OBJECT | INPUT_FIELD_DEFINITION
directive @myCustomDirective2 on OBJECT | FIELD_DEFINITION | INPUT_OBJECT | INPUT_FIELD_DEFINITION

directive @someDirective1 on OBJECT

type MyTypeWithCustomDirectiveOnObject
@myCustomDirective
@myCustomDirective2
@someDirective1 {
field: String
}

type MyTypeWithCustomDirectiveOnField {
field: String @myCustomDirective
}

input MyInputWithCustomDirectiveOnObject @myCustomDirective {
field: String
}

input MyInputWithCustomDirectiveOnField {
field: String @myCustomDirective
}