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