Spike: Evaluate approaches to parse and manipulate TypeScript source code
Use cases:
- Emit
design:typefor advanced types such asPromise<Customer>,Partial<Customer>,Customer[], andnumber | string. - Update generated TS files for models/datasources/controllers/repositories/ e.g.
lb4 relation(models and repositories) #1359
Existing modules:
- https://github.com/strongloop/loopback-next/issues/1359#issuecomment-416813115
- https://github.com/dsherret/ts-simple-ast
Hi @raymondfeng, I would like to get this tech spike assigned to me for investigation. I have managed to manipulate TypeScript files using the TypeScript compiler's AST API. Will post here soon my findings relation-wise.
@raymondfeng
Using the listed ts-simple-ast package, I have managed to manipulate TypeScript files.
More specifically - I have created hardcoded haMany relation for a model and repository files.
I do not see any problems doing similar manipulations to a controller file.
Regarding dataSource manipulation - not sure what should be written there when adding new relations. Can you please elaborate?
Here is an example for a simple (hardcoded) model file manipulation:
import {Project, SourceFile} from 'ts-simple-ast';
const project = new Project();
const sourceFile = project.addExistingSourceFile('./src/models/todo.model.ts');
addModelHasMany(sourceFile);
function addModelHasMany(modelFile: SourceFile): void {
let classes = sourceFile.getClasses();
let classBody = classes[0];
classBody.addProperty({
hasQuestionToken: true,
name: 'todoLists',
type: 'TodoList[]',
decorators: [{name: 'hasMany', arguments: ['() => TodoList']}],
});
// prints the output of the manipulated file
console.log(sourceFile.getFullText());
project.save();
}
In addition, I also managed to create custom types such as Promise<Customer> using code-block-writer.
@orshlom, thanks for the investigation. @b-admike, could you also please take a look at the above comments from @orshlom?
@orshlom
Using the listed
ts-simple-astpackage, I have managed to manipulate TypeScript files. In addition, I also managed to create custom types such as Promiseusing code-block-writer.
This is awesome! Would you mind sharing the code you wrote to manipulate TypeScript files? That way we can review it and hopefully close this spike as done.
@orshlom I am not too familiar with ts-simple-ast but the results look pretty good IMO 👍. +1 for sharing the PoC code for review.
@dhmlau I think this issue can be closed. All the work in https://github.com/strongloop/loopback-next/pull/2426 was done using AST.