Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] Idiomatic way to insert before the return statement of a function? #1493

Open
melMass opened this issue Jan 24, 2024 · 0 comments

Comments

@melMass
Copy link

melMass commented Jan 24, 2024

Hi,

Thanks for this project.
I'm trying a simple automatic implementation à la Rust macros. I have a crude POC that is almost working:

//- find all createXXXStore methods
project.getSourceFiles().forEach((sourceFile) => {
const func: FunctionDeclaration | undefined = sourceFile.getFunction((f) => {
    const func_name = f.getName();
    if (func_name) {
      const low = func_name.toLowerCase();
      return low.startsWith("create") && low.endsWith("store");
    }
    return false;
  });
  if (!func) return;

  //- extract the store type from the first parameter
  const initial_type = func.getParameters()[0];
  const props = initial_type.getType().getProperties();
  
  //- from each properties of our type we extract information to create setters.
  props.forEach((p) => {
    const name = p.getName();
    const kind = p.getTypeAtLocation(initial_type);
    //- naive way to get the location before the return block
    const child_location = func.getChildCount() - 1;
    //- make our setter
    const setter = func.insertFunction(child_location, {
      name: toCamelCase("set-" + name),
      leadingTrivia: "// autogenerated with ts-morph",
      statements: `update((state) => {
            return {
              ...state,
              ${name},
            };
          });`,
      parameters: [
        {
          name: name,
          type: kind.getText(),
        },
      ],
    });
  });
console.log(sourceFile.print({}));
});

TLDR

func.getChildCount() in the above code does not return the proper value: InvalidOperationError: Invalid index: The max index is 4, but 5 was specified. so childCount returned 6 instead of the 4 children the method has

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant