Ts-Morph function call Identiier

60 Views Asked by At

I currently have a file with this router methods (see below):

import { Router } from "express";
import { createSubscriber, deleteSubscriberById, getAllSubscribers, getSubscriberById, getSubscriberMiddleware, updateSubscriberById } from "./subscribers";


const router = Router()

router.get("/", getAllSubscribers)

router.get("/:id", getSubscriberMiddleware, getSubscriberById)

router.post("/", createSubscriber)


router.patch("/:id", getSubscriberMiddleware, updateSubscriberById)


router.delete("/:id", getSubscriberMiddleware, deleteSubscriberById)


export default router;

I want to be able to identify the middleware and the controller functions/methods using TS-Morph library.

I have tried using CallExpression but still could not get it to work.

I have tried using CallExpression but still could not get it to work.

  const functions = currentSourceFile.getFunctions();

  const importedFunctionsMap: Map<string, SourceFile> = new Map();

  functions.forEach((func) => {
    func.forEachDescendant((node) => {
      if (node.getKindName() === "CallExpression") {
        const callee = node.getFirstChildByKind(SyntaxKind.Identifier);
        if (callee) {
          const dependencyFunctionName = callee.getText();

          const importedFunctionDeclaration = currentSourceFile.getImportDeclaration(
            (importDeclaration) => importDeclaration.getNamedImports().some((spec) => spec.getText() === dependencyFunctionName)
          );

          if (importedFunctionDeclaration && !isNodeModuleImport(importedFunctionDeclaration)) {
            const sourceFile = importedFunctionDeclaration.getModuleSpecifierSourceFile();
            if (sourceFile) {
              importedFunctionsMap.set(dependencyFunctionName, sourceFile);
            }
          }
        }
      }
    });
  });
0

There are 0 best solutions below