|
| 1 | +import { type Operation, getDeprecationDetails, isArrayModelType } from "@typespec/compiler"; |
| 2 | +import * as gql from "@alloy-js/graphql"; |
| 3 | +import { useTsp } from "@typespec/emitter-framework"; |
| 4 | +import { resolveGraphQLTypeName } from "../../lib/graphql-type-name.js"; |
| 5 | +import { hasNullableElements, isNullable } from "../../lib/nullable.js"; |
| 6 | + |
| 7 | +export interface OperationFieldProps { |
| 8 | + operation: Operation; |
| 9 | +} |
| 10 | + |
| 11 | +export function OperationField(props: OperationFieldProps) { |
| 12 | + const { $, program } = useTsp(); |
| 13 | + |
| 14 | + const doc = $.type.getDoc(props.operation); |
| 15 | + const deprecation = getDeprecationDetails(program, props.operation); |
| 16 | + const returnType = props.operation.returnType; |
| 17 | + const nullable = isNullable(props.operation); |
| 18 | + const params = Array.from(props.operation.parameters.properties.values()); |
| 19 | + |
| 20 | + const isList = returnType.kind === "Model" && isArrayModelType(returnType); |
| 21 | + const typeName = isList |
| 22 | + ? resolveGraphQLTypeName(returnType.indexer.value) |
| 23 | + : resolveGraphQLTypeName(returnType); |
| 24 | + const elemNullable = isList && hasNullableElements(props.operation); |
| 25 | + |
| 26 | + return ( |
| 27 | + <gql.Field |
| 28 | + name={props.operation.name} |
| 29 | + type={typeName} |
| 30 | + nonNull={isList ? !elemNullable : !nullable} |
| 31 | + description={doc} |
| 32 | + deprecated={deprecation?.message} |
| 33 | + > |
| 34 | + {isList ? <gql.Field.List nonNull={!nullable} /> : undefined} |
| 35 | + {params.map((param) => { |
| 36 | + const paramNullable = isNullable(param) || param.optional; |
| 37 | + const paramType = param.type; |
| 38 | + const paramIsList = paramType.kind === "Model" && isArrayModelType(paramType); |
| 39 | + const paramElemNullable = paramIsList && hasNullableElements(param); |
| 40 | + const paramTypeName = paramIsList |
| 41 | + ? resolveGraphQLTypeName(paramType.indexer.value) |
| 42 | + : resolveGraphQLTypeName(paramType); |
| 43 | + |
| 44 | + return ( |
| 45 | + <gql.InputValue |
| 46 | + name={param.name} |
| 47 | + type={paramTypeName} |
| 48 | + nonNull={paramIsList ? !paramElemNullable : !paramNullable} |
| 49 | + description={$.type.getDoc(param)} |
| 50 | + deprecated={getDeprecationDetails(program, param)?.message} |
| 51 | + > |
| 52 | + {paramIsList ? <gql.InputValue.List nonNull={!paramNullable} /> : undefined} |
| 53 | + </gql.InputValue> |
| 54 | + ); |
| 55 | + })} |
| 56 | + </gql.Field> |
| 57 | + ); |
| 58 | +} |
0 commit comments