Skip to content

Commit

Permalink
refactor: getAssertion
Browse files Browse the repository at this point in the history
  • Loading branch information
skarab42 committed Jul 12, 2022
1 parent af1eda0 commit c2bb6f6
Showing 1 changed file with 26 additions and 14 deletions.
40 changes: 26 additions & 14 deletions src/plugin/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,24 +32,36 @@ export function transform({ code, fileName, report, typescript }: TransformSetti
};
}

export function getAssertion(node: ts.Node, typeChecker: ts.TypeChecker): Assertion | undefined {
if (!ts.isCallExpression(node)) {
return undefined;
}

const expression = node.expression;
const expressionType = typeChecker.getTypeAtLocation(expression);
const assertionProperty = expressionType.getProperty(API_PROPERTY_KEY);

if (assertionProperty) {
const assertionPropertyType = typeChecker.getTypeOfSymbolAtLocation(assertionProperty, expression);
const assertionPropertyValue = typeChecker.typeToString(assertionPropertyType).slice(1, -1);
const [apiName, functionName] = assertionPropertyValue.split(':');

if (apiName && functionName) {
return { apiName: apiName as APIName, functionName, node };
}
}

return undefined;
}

function getAssertions(sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker): Assertion[] {
const assertions: Assertion[] = [];

function visit(node: ts.Node): void {
if (ts.isCallExpression(node)) {
const expression = node.expression;
const expressionType = typeChecker.getTypeAtLocation(expression);
const assertionProperty = expressionType.getProperty(API_PROPERTY_KEY);

if (assertionProperty) {
const assertionPropertyType = typeChecker.getTypeOfSymbolAtLocation(assertionProperty, expression);
const assertionPropertyValue = typeChecker.typeToString(assertionPropertyType).slice(1, -1);
const [apiName, functionName] = assertionPropertyValue.split(':');

if (apiName && functionName) {
assertions.push({ apiName: apiName as APIName, functionName, node });
}
}
const assertion = getAssertion(node, typeChecker);

if (assertion) {
assertions.push(assertion);
}

node.forEachChild(visit);
Expand Down

0 comments on commit c2bb6f6

Please sign in to comment.