ts-morph#StatementStructures TypeScript Examples

The following examples show how to use ts-morph#StatementStructures. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConfigGenerator.ts    From gengen with MIT License 6 votes vote down vote up
public getConfigCodeStructure(): StatementStructures[] {
        return [
            {
                kind: StructureKind.ImportDeclaration,
                moduleSpecifier: `./${configOptions.className.toLowerCase()}`,
                namedImports: [{ name: configOptions.className }]
            },
            {
                kind: StructureKind.ExportAssignment,
                expression: 'new Set<string>([])',
                isExportEquals: false
            }
        ];
    }
Example #2
Source File: ConfigGenerator.ts    From gengen with MIT License 6 votes vote down vote up
public getEndpointsCodeStructure(controllers: Record<string, Record<string, string>>): StatementStructures[] {
        return [
            {
                kind: StructureKind.Class,
                isExported: true,
                name: configOptions.className,
                properties: this.getProperties(controllers)
            }
        ];
    }
Example #3
Source File: ModelsGenerator.ts    From gengen with MIT License 6 votes vote down vote up
public getModelsCodeStructure(models: IModelsContainer): StatementStructures[] {
        return [
            ...this.getImports(),
            ...this.getEnums(models.enums),
            ...this.interfaceGenerator.getCodeStructure(models.interfaces),
            ...this.getIdentities(models.identities, models.interfaces),
            ...this.getObjects(models.objects)
        ];
    }
Example #4
Source File: ModelsGenerator.ts    From gengen with MIT License 6 votes vote down vote up
private getIdentities(identities: IIdentityModel[], interfaces: IInterfaceModel[]): StatementStructures[] {
        return identities.map(
            (z): ClassDeclarationStructure => ({
                kind: StructureKind.Class,
                isExported: true,
                name: z.name,
                ctors: [
                    {
                        parameters: [
                            {
                                name: z.property.name,
                                hasQuestionToken: true,
                                type: TypeSerializer.fromTypeName(`${z.property.type} | ${z.property.dtoType}`).toString()
                            }
                        ] as OptionalKind<ParameterDeclarationStructure>[],
                        statements: `this.${z.property.name} = new ${z.property.type}(${z.property.name});`
                    }
                ] as OptionalKind<ConstructorDeclarationStructure>[],
                properties: [{ scope: Scope.Public, name: z.property.name, type: z.property.type }, this.getGuardProperty(z.name)],
                methods: [
                    {
                        scope: Scope.Public,
                        isStatic: true,
                        name: TO_DTO_METHOD,
                        parameters: [{ name: z.property.name, type: z.property.type }],
                        returnType: interfaces.find(
                            (i) =>
                                i.properties.length === 1 &&
                                i.properties.every((x) => x.dtoType === z.property.dtoType && x.name === z.property.name)
                        )?.name,
                        statements: `return { ${z.property.name}: ${z.property.name}.toString() };`
                    }
                ]
            })
        );
    }
Example #5
Source File: GenGenCodeGen.ts    From gengen with MIT License 6 votes vote down vote up
protected generateProject(modelsCode: StatementStructures[], servicesCode: StatementStructures[]): Project {
        const project = new Project(generatorsOptions);

        project
            .createSourceFile(
                `${this.options.output}/${this.injector.aliasResolver.getModelsFileName()}`,
                { statements: modelsCode },
                { overwrite: true }
            )
            .formatText();

        project
            .createSourceFile(
                `${this.options.output}/${this.injector.aliasResolver.getServicesFileName()}`,
                { statements: servicesCode },
                { overwrite: true }
            )
            .formatText();

        return project;
    }
Example #6
Source File: model-output-type.ts    From prisma-nestjs-graphql with MIT License 6 votes vote down vote up
function getExportDeclaration(name: string, statements: StatementStructures[]) {
  return statements.find(structure => {
    return (
      structure.kind === StructureKind.ExportDeclaration &&
      (structure.namedExports as ExportSpecifierStructure[]).some(
        o => (o.alias || o.name) === name,
      )
    );
  });
}
Example #7
Source File: ModelsGenerator.ts    From gengen with MIT License 5 votes vote down vote up
private getEnums(enums: IEnumModel[]): StatementStructures[] {
        return enums.map((z) => ({
            kind: StructureKind.Enum,
            isExported: true,
            name: z.name,
            members: z.items.map((x) => ({ name: x.key, value: x.value }))
        }));
    }
Example #8
Source File: AngularServicesGenerator.ts    From gengen with MIT License 5 votes vote down vote up
public getServicesCodeStructure(services: IServiceModel[]): StatementStructures[] {
        return [...this.getImports(), ...this.getServices(services)];
    }
Example #9
Source File: generate-files.ts    From prisma-nestjs-graphql with MIT License 4 votes vote down vote up
export async function generateFiles(args: EventArguments) {
  const { project, config, output, eventEmitter } = args;

  if (config.emitSingle) {
    const rootDirectory =
      project.getDirectory(output) || project.createDirectory(output);
    const sourceFile =
      rootDirectory.getSourceFile('index.ts') ||
      rootDirectory.createSourceFile('index.ts', undefined, { overwrite: true });
    const statements = project.getSourceFiles().flatMap(s => {
      if (s === sourceFile) {
        return [];
      }
      const classDeclaration = s.getClass(() => true);
      const statements = s.getStructure().statements;
      // Reget decorator full name
      // TODO: Check possible bug of ts-morph
      if (Array.isArray(statements)) {
        for (const statement of statements) {
          if (
            !(typeof statement === 'object' && statement.kind === StructureKind.Class)
          ) {
            continue;
          }
          for (const property of statement.properties || []) {
            for (const decorator of property.decorators || []) {
              const fullName = classDeclaration
                ?.getProperty(property.name)
                ?.getDecorator(decorator.name)
                ?.getFullName();
              ok(
                fullName,
                `Cannot get full name of decorator of class ${statement.name!}`,
              );
              decorator.name = fullName;
            }
          }
        }
      }

      project.removeSourceFile(s);
      return statements;
    });
    const imports = new ImportDeclarationMap();
    const enums: (StatementStructures | string)[] = [];
    const classes: ClassDeclarationStructure[] = [];
    for (const statement of statements as (StatementStructures | string)[]) {
      if (typeof statement === 'string') {
        if (statement.startsWith('registerEnumType')) {
          enums.push(statement);
        }
        continue;
      }
      switch (statement.kind) {
        case StructureKind.ImportDeclaration:
          if (
            statement.moduleSpecifier.startsWith('./') ||
            statement.moduleSpecifier.startsWith('..')
          ) {
            continue;
          }
          for (const namedImport of statement.namedImports as ImportSpecifierStructure[]) {
            const name = namedImport.alias || namedImport.name;
            imports.add(name, statement.moduleSpecifier);
          }
          if (statement.defaultImport) {
            imports.create({
              from: statement.moduleSpecifier,
              name: statement.defaultImport,
              defaultImport: statement.defaultImport,
            });
          }
          if (statement.namespaceImport) {
            imports.create({
              from: statement.moduleSpecifier,
              name: statement.namespaceImport,
              namespaceImport: statement.namespaceImport,
            });
          }
          break;
        case StructureKind.Enum:
          enums.unshift(statement);
          break;
        case StructureKind.Class:
          classes.push(statement);
          break;
      }
    }
    sourceFile.set({
      kind: StructureKind.SourceFile,
      statements: [...imports.toStatements(), ...enums, ...classes],
    });
  }

  if (config.emitCompiled) {
    project.compilerOptions.set({
      declaration: true,
      declarationDir: output,
      rootDir: output,
      outDir: output,
      emitDecoratorMetadata: false,
      skipLibCheck: true,
    });
    const emitResult = await project.emit();
    const errors = emitResult.getDiagnostics().map(d => String(d.getMessageText()));
    if (errors.length > 0) {
      eventEmitter.emitSync('Warning', errors);
    }
  } else {
    await project.save();
  }
}
Example #10
Source File: model-output-type.ts    From prisma-nestjs-graphql with MIT License 4 votes vote down vote up
export function modelOutputType(outputType: OutputType, args: EventArguments) {
  const { getSourceFile, models, config, modelFields, fieldSettings, eventEmitter } =
    args;
  const model = models.get(outputType.name);
  ok(model, `Cannot find model by name ${outputType.name}`);

  const sourceFile = getSourceFile({
    name: outputType.name,
    type: 'model',
  });
  const sourceFileStructure = sourceFile.getStructure();
  const exportDeclaration = getExportDeclaration(
    model.name,
    sourceFileStructure.statements as StatementStructures[],
  );
  const importDeclarations = new ImportDeclarationMap();
  const classStructure: ClassDeclarationStructure = {
    kind: StructureKind.Class,
    isExported: true,
    name: outputType.name,
    decorators: [
      {
        name: 'ObjectType',
        arguments: [],
      },
    ],
    properties: [],
  };
  (sourceFileStructure.statements as StatementStructures[]).push(classStructure);
  ok(classStructure.decorators, 'classStructure.decorators is undefined');
  const decorator = classStructure.decorators.find(d => d.name === 'ObjectType');
  ok(decorator, 'ObjectType decorator not found');

  let modelSettings: ObjectSettings | undefined;
  // Get model settings from documentation
  if (model.documentation) {
    const objectTypeOptions: PlainObject = {};
    const { documentation, settings } = createObjectSettings({
      text: model.documentation,
      config,
    });
    if (documentation) {
      if (!classStructure.leadingTrivia) {
        classStructure.leadingTrivia = createComment(documentation);
      }
      objectTypeOptions.description = documentation;
    }
    decorator.arguments = settings.getObjectTypeArguments(objectTypeOptions);
    modelSettings = settings;
  }

  importDeclarations.add('Field', nestjsGraphql);
  importDeclarations.add('ObjectType', nestjsGraphql);

  for (const field of outputType.fields) {
    let fileType = 'model';
    const { location, isList, type, namespace } = field.outputType;

    let outputTypeName = String(type);
    if (namespace !== 'model') {
      fileType = 'output';
      outputTypeName = getOutputTypeName(outputTypeName);
    }
    const modelField = modelFields.get(model.name)?.get(field.name);
    const settings = fieldSettings.get(model.name)?.get(field.name);
    const fieldType = settings?.getFieldType({
      name: outputType.name,
      output: true,
    });
    const propertySettings = settings?.getPropertyType({
      name: outputType.name,
      output: true,
    });

    const propertyType = castArray(
      propertySettings?.name ||
        getPropertyType({
          location,
          type: outputTypeName,
        }),
    );

    // For model we keep only one type
    propertyType.splice(1, propertyType.length);

    if (field.isNullable && !isList) {
      propertyType.push('null');
    }

    let graphqlType: string;

    if (fieldType) {
      graphqlType = fieldType.name;
      importDeclarations.create({ ...fieldType });
    } else {
      const graphqlImport = getGraphqlImport({
        config,
        sourceFile,
        fileType,
        location,
        isId: modelField?.isId,
        noTypeId: config.noTypeId,
        typeName: outputTypeName,
        getSourceFile,
      });

      graphqlType = graphqlImport.name;

      if (graphqlImport.name !== outputType.name && graphqlImport.specifier) {
        importDeclarations.add(graphqlImport.name, graphqlImport.specifier);
      }
    }

    const property = propertyStructure({
      name: field.name,
      isNullable: field.isNullable,
      hasExclamationToken: true,
      hasQuestionToken: location === 'outputObjectTypes',
      propertyType,
      isList,
    });

    if (typeof property.leadingTrivia === 'string' && modelField?.documentation) {
      property.leadingTrivia += createComment(modelField.documentation, settings);
    }

    classStructure.properties?.push(property);

    if (propertySettings) {
      importDeclarations.create({ ...propertySettings });
    } else if (propertyType.includes('Decimal')) {
      importDeclarations.add('Decimal', '@prisma/client/runtime');
    }

    ok(property.decorators, 'property.decorators is undefined');

    if (settings?.shouldHideField({ name: outputType.name, output: true })) {
      importDeclarations.add('HideField', nestjsGraphql);
      property.decorators.push({ name: 'HideField', arguments: [] });
    } else {
      // Generate `@Field()` decorator
      property.decorators.push({
        name: 'Field',
        arguments: [
          isList ? `() => [${graphqlType}]` : `() => ${graphqlType}`,
          JSON5.stringify({
            ...settings?.fieldArguments(),
            nullable: Boolean(field.isNullable),
            defaultValue: ['number', 'string', 'boolean'].includes(
              typeof modelField?.default,
            )
              ? modelField?.default
              : undefined,
            description: modelField?.documentation,
          }),
        ],
      });

      for (const setting of settings || []) {
        if (shouldBeDecorated(setting) && (setting.match?.(field.name) ?? true)) {
          property.decorators.push({
            name: setting.name,
            arguments: setting.arguments as string[],
          });
          ok(setting.from, "Missed 'from' part in configuration or field setting");
          importDeclarations.create(setting);
        }
      }

      for (const decorate of config.decorate) {
        if (decorate.isMatchField(field.name) && decorate.isMatchType(outputTypeName)) {
          property.decorators.push({
            name: decorate.name,
            arguments: decorate.arguments?.map(x => pupa(x, { propertyType })),
          });
          importDeclarations.create(decorate);
        }
      }
    }

    eventEmitter.emitSync('ClassProperty', property, {
      location,
      isList,
      propertyType,
    });
  }

  // Generate class decorators from model settings
  for (const setting of modelSettings || []) {
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
    if (shouldBeDecorated(setting)) {
      classStructure.decorators.push({
        name: setting.name,
        arguments: setting.arguments as string[],
      });
      importDeclarations.create(setting);
    }
  }

  if (exportDeclaration) {
    sourceFile.set({
      statements: [exportDeclaration, '\n', classStructure],
    });
    const classDeclaration = sourceFile.getClassOrThrow(model.name);
    const commentedText = classDeclaration
      .getText()
      .split('\n')
      .map(x => `// ${x}`);
    classDeclaration.remove();
    sourceFile.addStatements(['\n', ...commentedText]);
  } else {
    sourceFile.set({
      statements: [...importDeclarations.toStatements(), classStructure],
    });
  }
}