Skip to content

Commit 2400d78

Browse files
committed
feat(graphql): add EnumTypeMap for GraphQL enum materialization
1 parent 2079c67 commit 2400d78

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

packages/graphql/src/type-maps.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ export interface TSPContext<T extends Type> {
1515
/**
1616
* Nominal type for keys in the TypeMap
1717
*/
18-
type TypeKey = string & { __typeKey: any };
18+
export type TypeKey = string & { __typeKey: any };
1919

2020
/**
2121
* Base TypeMap for all GraphQL type mappings
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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 context.
14+
* Uses graphqlName override if provided, otherwise uses the enum's name.
15+
*/
16+
protected getNameFromContext(context: TSPContext<Enum>): TypeKey {
17+
return (context.graphqlName ?? context.type.name) as TypeKey;
18+
}
19+
20+
/**
21+
* Materializes a TypeSpec Enum into a GraphQL EnumType.
22+
*/
23+
protected materialize(context: TSPContext<Enum>): GraphQLEnumType {
24+
const tspEnum = context.type;
25+
const name = context.graphqlName ?? tspEnum.name;
26+
27+
return new GraphQLEnumType({
28+
name,
29+
values: Object.fromEntries(
30+
Array.from(tspEnum.members.values()).map((member) => [
31+
member.name,
32+
{ value: member.value ?? member.name },
33+
]),
34+
),
35+
});
36+
}
37+
}
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)