All files / utils typescript-utils.ts

100% Statements 55/55
100% Branches 12/12
100% Functions 3/3
100% Lines 55/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 561x 1x 1x 3x 3x 3x 2x 2x 2x 3x 3x 3x 1x 1x 28x 28x 28x 28x 28x 29x 29x 29x 29x 29x 29x 29x 1x 1x 28x 28x 28x 29x 8x 8x 8x 8x 8x 28x 28x 28x 28x 28x 28x 28x 28x 29x 28x 28x 1x 2x 1x 28x 27x 27x 28x  
import type { SourceFile } from "ts-morph";
 
export function getOrCreateConstructor(sourceFile: SourceFile) {
  let constructor = sourceFile.getClasses()[0].getConstructors()[0];
 
  if (!constructor) {
    // Create the constructor if it does not exist
    constructor = sourceFile.getClasses()[0].addConstructor();
  }
 
  return constructor;
}
 
export function addImportToClass(
  sourceFile: SourceFile,
  importName: string | string[],
  moduleSpecifier: string,
) {
  const addImport = (
    sourceFile: SourceFile,
    importName: string,
    moduleSpecifier: string,
  ) => {
    const classDeclaration = sourceFile.getClasses()[0];
 
    if (!classDeclaration) {
      return;
    }
 
    let importDeclaration = sourceFile.getImportDeclaration(moduleSpecifier);
 
    if (!importDeclaration) {
      // Create the import declaration if it does not exist.
      importDeclaration = sourceFile.addImportDeclaration({
        moduleSpecifier,
      });
    }
 
    const importSpecifier = importDeclaration
      .getNamedImports()
      .find((n) => n.getName() === importName);
 
    if (!importSpecifier) {
      importDeclaration.addNamedImport(importName);
    }
  };
 
  if (Array.isArray(importName)) {
    importName.forEach((name) => {
      addImport(sourceFile, name, moduleSpecifier);
    });
  } else {
    addImport(sourceFile, importName, moduleSpecifier);
  }
}