Skip to content

Commit f410002

Browse files
committed
feat(graphql): add EnumTypeMap for GraphQL enum materialization
1 parent e651f96 commit f410002

File tree

3 files changed

+40
-3
lines changed

3 files changed

+40
-3
lines changed

packages/graphql/src/type-maps.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,13 @@ import type { GraphQLType } from "graphql";
88
export interface TSPContext<T extends Type> {
99
type: T; // The TypeSpec type
1010
usageFlag: UsageFlags; // How the type is being used (input, output, etc.)
11-
graphqlName?: string; // Optional GraphQL type name override (e.g., "ModelInput" for input types)
12-
metadata: Record<string, any>; // Additional metadata
11+
metadata?: Record<string, any>; // Optional additional metadata
1312
}
1413

1514
/**
1615
* Nominal type for keys in the TypeMap
1716
*/
18-
type TypeKey = string & { __typeKey: any };
17+
export type TypeKey = string & { __typeKey: any };
1918

2019
/**
2120
* Base TypeMap for all GraphQL type mappings
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import type { Enum } from "@typespec/compiler";
2+
import { GraphQLEnumType } from "graphql";
3+
import { TypeMap, type TSPContext, type TypeKey } from "../type-maps.js";
4+
5+
/**
6+
* TypeMap for converting TypeSpec Enums to GraphQL EnumTypes.
7+
*
8+
* Handles registration of TSP enums and lazy materialization into
9+
* GraphQLEnumType instances.
10+
*/
11+
export class EnumTypeMap extends TypeMap<Enum, GraphQLEnumType> {
12+
/**
13+
* Derives the type key from the mutated enum's name.
14+
*/
15+
protected getNameFromContext(context: TSPContext<Enum>): TypeKey {
16+
return context.type.name as TypeKey;
17+
}
18+
19+
/**
20+
* Materializes a TypeSpec Enum into a GraphQL EnumType.
21+
*/
22+
protected materialize(context: TSPContext<Enum>): GraphQLEnumType {
23+
const tspEnum = context.type;
24+
const name = tspEnum.name;
25+
26+
return new GraphQLEnumType({
27+
name,
28+
values: Object.fromEntries(
29+
Array.from(tspEnum.members.values()).map((member) => [
30+
member.name,
31+
{ value: member.value ?? member.name },
32+
]),
33+
),
34+
});
35+
}
36+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export { TypeMap, type TSPContext, type TypeKey } from "../type-maps.js";
2+
export { EnumTypeMap } from "./enum.js";

0 commit comments

Comments
 (0)