adding function to export the used interfaces etc

This commit is contained in:
Martin Karkowski 2020-08-23 09:25:10 +02:00
parent 7adb65fef2
commit f946a6107c

View File

@ -0,0 +1,82 @@
import { SourceFile } from "ts-morph";
import { createFileMapping, analyzeClasses, getDeclarationByName } from "./analyzeTypescriptFiles";
/**
* Function, that will create the imported Type classes based on source-Files.
* @param sourceFiles
* @param options Options, to Controll the generation.
*/
export function transformClasses(sourceFiles: SourceFile[], options: {
classDecorator: string,
classInterface: string,
methodDecorator: string,
propertyType: string,
propertyDecorator: string,
} = {
classDecorator: 'exportsElementsToDispatcher',
classInterface: '',
methodDecorator: 'exportMethodToDispatcher',
propertyType: 'nopeObservable',
propertyDecorator: 'exportPropertyToDispatcher'
}){
const fileMapping = createFileMapping(sourceFiles);
const classes = analyzeClasses(sourceFiles, options);
// Iterate over the Classes
for (const relevantClass of classes){
const requiredImports = new Set<string>();
const mappingTypeToImport: {
[index: string]: Set<string>
} = {}
// Iterate over the Properties
for (const prop of relevantClass.properties){
if (!prop.isBaseType){
for (const {identifier: type, path} of (prop.typeImports || [])){
// Only if the import isnt the Base Type, add it to the List.
if (type !== options.propertyType) {
// Check if the Imported Type has been Adden multiple Times.
if (mappingTypeToImport[type] === undefined) {
mappingTypeToImport[type] = new Set<string>();
}
mappingTypeToImport[type].add(path);
requiredImports.add(type);
}
}
}
}
let fileWithTypesForClass = ''
for (const reqType of requiredImports) {
if (mappingTypeToImport[reqType] && mappingTypeToImport[reqType].size === 1) {
// Extract the Path of the File
const pathToFile = Array.from(mappingTypeToImport[reqType].values())[0] + '.ts';
const declarations = getDeclarationByName(fileMapping, pathToFile, reqType);
fileWithTypesForClass += declarations.map(item =>
item.originalCode
).reduce(
(prev, current, idx) =>
// If it is the First Element => Skipp the New Line Property idx === 0 ? current:
prev + '\n\n' + current,
`// Automatic extracted Interfaces for the Class "` + relevantClass.className + `"
// Generated on: ` + (new Date()).toISOString()
);
} else if (mappingTypeToImport[reqType].size > 1) {
// Multiple Items are using the Same Name.
}
}
console.log(fileWithTypesForClass)
}
}