Skip to content

Commit

Permalink
Add union types of different message classes
Browse files Browse the repository at this point in the history
  • Loading branch information
Roaders committed Oct 15, 2024
1 parent 2b20e62 commit 6cf70dc
Show file tree
Hide file tree
Showing 4 changed files with 832 additions and 87 deletions.
16 changes: 15 additions & 1 deletion code-generation/generate-type-predicates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,33 @@ const matchedInterfaces = convertFunctions.map(func => {
// write a type predicate for each matched interface
matchedInterfaces.forEach(matched => writePredicate(matched.matchingInterface, matched.func));

writeUnionType("RequestMessage", interfaces, "Request");
writeUnionType("ResponseMessage", interfaces, "Response");
writeUnionType("EventMessage", interfaces, "Event");

function writePredicate(matchingInterface: InterfaceDeclaration, func: MethodDeclaration): void{
const predicateName = `is${matchingInterface.getName()}`;

sourceFile.addStatements(`export function ${predicateName}(value: any): value is ${matchingInterface.getName()} {
sourceFile.addStatements(`
export function ${predicateName}(value: any): value is ${matchingInterface.getName()} {
try{
Convert.${func.getName()}(value);
return true;
} catch(e: any){
return false;
}
}`);
}



function writeUnionType(unionName: string, interfaces: InterfaceDeclaration[], nameEndsWith: string): void{
const matchingInterfaces = interfaces
.map(currentInterface => currentInterface.getName())
.filter(interfaceName => interfaceName.length > nameEndsWith.length && interfaceName.indexOf(nameEndsWith) === interfaceName.length - nameEndsWith.length);

sourceFile.addStatements(`
export type ${unionName} = ${matchingInterfaces.join(" | ")};`);
}

sourceFile.formatText();
Expand Down
Loading

0 comments on commit 6cf70dc

Please sign in to comment.