awesome-cordova-plugins/scripts/build/transformers/methods.ts

63 lines
1.8 KiB
TypeScript
Raw Normal View History

2017-12-28 20:28:44 +08:00
import * as ts from 'typescript';
2017-12-29 12:15:34 +08:00
import { Logger } from '../../logger';
2020-05-16 20:40:49 +08:00
import {
convertValueToLiteral,
getDecorator,
getDecoratorArgs,
getDecoratorName,
getMethodsForDecorator,
} from '../helpers';
2017-12-28 20:28:44 +08:00
export function transformMethod(method: ts.MethodDeclaration) {
if (!method) return;
const decorator = getDecorator(method),
decoratorName = getDecoratorName(decorator),
decoratorArgs = getDecoratorArgs(decorator);
try {
2020-05-16 20:40:49 +08:00
return ts.createMethod(
undefined,
undefined,
undefined,
method.name,
undefined,
method.typeParameters,
method.parameters,
method.type,
ts.createBlock([ts.createReturn(getMethodBlock(method, decoratorName, decoratorArgs))])
);
2017-12-28 20:28:44 +08:00
} catch (e) {
2017-12-29 12:15:34 +08:00
Logger.error('Error transforming method: ' + (method.name as any).text);
Logger.error(e.message);
2017-12-28 20:28:44 +08:00
}
}
function getMethodBlock(method: ts.MethodDeclaration, decoratorName: string, decoratorArgs: any): ts.Expression {
const decoratorMethod = getMethodsForDecorator(decoratorName)[0];
switch (decoratorName) {
case 'CordovaCheck':
case 'InstanceCheck':
// TODO remove function wrapper
2020-05-16 20:40:49 +08:00
return ts.createImmediatelyInvokedArrowFunction([
ts.createIf(
ts.createBinary(
ts.createCall(ts.createIdentifier(decoratorMethod), undefined, [ts.createThis()]),
ts.SyntaxKind.EqualsEqualsEqualsToken,
ts.createTrue()
),
method.body
2017-12-28 20:28:44 +08:00
),
2020-05-16 20:40:49 +08:00
]);
2017-12-28 20:28:44 +08:00
default:
return ts.createCall(ts.createIdentifier(decoratorMethod), undefined, [
ts.createThis(),
ts.createLiteral(decoratorArgs?.methodName || (method.name as any).text),
2017-12-28 20:28:44 +08:00
convertValueToLiteral(decoratorArgs),
2020-05-16 20:40:49 +08:00
ts.createIdentifier('arguments'),
2017-12-28 20:28:44 +08:00
]);
}
}