import { Generatable, isScalarType } from './helpers'; import { DMMFDocument } from './transformDMMF'; import { DMMF } from '@prisma/generator-helper'; type TypesGeneratorStructure = { inputTypes: TGType[]; outputTypes: TGType[]; // TODO: evaluate calling them enums as that can be ambigious //enums: any; }; type TGType = { name: string; fields: TGTypeField[]; }; type TGTypeField = { name: string; type: DMMF.SchemaArgInputType[]; nullable: boolean; }; class TypesGenerator implements Generatable { data: TypesGeneratorStructure; constructor(d: DMMFDocument) { this.data = this.getData(d); } getTypeFieldHTML( field: TGTypeField, kind: 'inputType' | 'outputType' ): string { return ` ${field.name} ${field.type .map((f) => isScalarType(f.type as string) ? f.type : `${f.type}${ f.isList ? '[]' : '' }` ) .join(' | ')} ${field.nullable ? 'Yes' : 'No'} `; } getTypeHTML(type: TGType, kind: 'inputType' | 'outputType'): string { return `

${ type.name }

${type.fields .map((field) => this.getTypeFieldHTML(field, kind)) .join('')}
Name Type Nullable
`; } toHTML() { return `

Types

Input Types

${this.data.inputTypes .map((inputType) => this.getTypeHTML(inputType, 'inputType')) .join(`
`)}

Output Types

${this.data.outputTypes .map((outputType) => this.getTypeHTML(outputType, 'outputType')) .join(`
`)}
`; } getInputTypes(dmmfInputType: DMMF.InputType[]): TGType[] { return dmmfInputType.map((inputType) => ({ name: inputType.name, fields: inputType.fields.map((ip) => ({ name: ip.name, nullable: ip.isNullable, type: ip.inputTypes, })), })); } getOutputTypes(dmmfOutputTypes: DMMF.OutputType[]): TGType[] { return dmmfOutputTypes.map((outputType) => ({ name: outputType.name, fields: outputType.fields.map((op) => ({ name: op.name, nullable: !op.isNullable, list: (op.outputType as any).isList, type: [ { isList: op.outputType.isList, type: op.outputType.type as string, location: op.outputType.location, }, ], })), })); } getData(d: DMMFDocument) { return { inputTypes: this.getInputTypes(d.schema.inputObjectTypes.prisma), outputTypes: this.getOutputTypes([ ...d.schema.outputObjectTypes.model, ...d.schema.outputObjectTypes.prisma.filter( (op) => op.name !== 'Query' && op.name !== 'Mutation' ), ]), }; } } export default TypesGenerator;