|
| 1 | +import {DataType} from "@code0-tech/sagittarius-graphql-types" |
| 2 | +import ts from "typescript" |
| 3 | +import {getSchema, Schema} from "../util/schema.util" |
| 4 | +import {createCompilerHost, getSharedTypeDeclarations} from "../utils" |
| 5 | + |
| 6 | +/** |
| 7 | + * Generates a schema for a given TypeScript type expression string. |
| 8 | + * |
| 9 | + * This function creates a virtual TypeScript environment, wraps the provided type expression |
| 10 | + * into a type alias 'T', and extracts the schema for it. |
| 11 | + * |
| 12 | + * @param typeString - The TypeScript type expression (e.g., "string | number" or "{ a: string }"). |
| 13 | + * @param dataTypes - An optional array of additional data type definitions to be included in the environment. |
| 14 | + * @returns The generated Schema for the identified type, or undefined if no valid type was found or an error occurred. |
| 15 | + */ |
| 16 | +export const getTypeSchema = ( |
| 17 | + typeString: string, |
| 18 | + dataTypes: DataType[] = [], |
| 19 | +): Schema | undefined => { |
| 20 | + const fileName = "index.ts" |
| 21 | + const typeDefs = getSharedTypeDeclarations(dataTypes) |
| 22 | + const sourceCode = `${typeDefs}\ntype MyType = ${typeString}` |
| 23 | + |
| 24 | + const host = createCompilerHost(fileName, sourceCode) |
| 25 | + const program = host.languageService.getProgram() |
| 26 | + const sourceFile = program?.getSourceFile(fileName) |
| 27 | + const checker = program?.getTypeChecker() |
| 28 | + |
| 29 | + if (!sourceFile || !checker) return undefined |
| 30 | + |
| 31 | + const targetStatement = sourceFile.statements |
| 32 | + .filter((stmt): stmt is ts.TypeAliasDeclaration | ts.InterfaceDeclaration | ts.ClassDeclaration => |
| 33 | + ts.isTypeAliasDeclaration(stmt) || ts.isInterfaceDeclaration(stmt) || ts.isClassDeclaration(stmt) |
| 34 | + ).pop() |
| 35 | + if (!targetStatement) return undefined |
| 36 | + |
| 37 | + const targetType = checker.getTypeAtLocation(targetStatement) |
| 38 | + if (!targetType) return undefined |
| 39 | + |
| 40 | + return getSchema(checker, undefined, targetType, [], [], false) |
| 41 | +} |
0 commit comments