1/* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import { SourceFile, SyntaxKind } from 'typescript'; 17import { MethodSignatureEntity } from '../declaration-node/methodSignatureDeclaration'; 18import { getCallbackStatement, getReturnStatement, getWarnConsole } from './generateCommonUtil'; 19 20/** 21 * generate interface signature method 22 * @param rootName 23 * @param methodSignatureArray 24 * @param sourceFile 25 * @returns 26 */ 27export function generateCommonMethodSignature(rootName: string, methodSignatureArray: Array<MethodSignatureEntity>, sourceFile: SourceFile): string { 28 let methodSignatureBody = ''; 29 const methodEntity = methodSignatureArray[0]; 30 methodSignatureBody += `${methodEntity.functionName}: function(...args) {`; 31 methodSignatureBody += getWarnConsole(rootName, methodEntity.functionName); 32 if (methodSignatureArray.length === 1) { 33 const args = methodEntity.args; 34 const len = args.length; 35 if (args.length > 0 && args[len - 1].paramName.toLowerCase().includes('callback')) { 36 methodSignatureBody += getCallbackStatement(); 37 } 38 if (methodEntity.returnType.returnKind !== SyntaxKind.VoidKeyword) { 39 if (rootName === 'Context' && methodEntity.returnType.returnKindName === 'Context') { 40 methodSignatureBody += 'return Context;'; 41 } else { 42 methodSignatureBody += getReturnStatement(methodEntity.returnType, sourceFile); 43 } 44 } 45 } else { 46 const argSet: Set<string> = new Set<string>(); 47 const returnSet: Set<string> = new Set<string>(); 48 let isCallBack = false; 49 methodSignatureArray.forEach(value => { 50 returnSet.add(value.returnType.returnKindName); 51 value.args.forEach(arg => { 52 argSet.add(arg.paramName); 53 if (arg.paramName.toLowerCase().includes('callback')) { 54 isCallBack = true; 55 } 56 }); 57 }); 58 if (isCallBack) { 59 methodSignatureBody += getCallbackStatement(); 60 } 61 let isReturnPromise = false; 62 returnSet.forEach(value => { 63 if (value.startsWith('Promise')) { 64 isReturnPromise = true; 65 } 66 }); 67 if (isReturnPromise && isCallBack) { 68 methodSignatureBody += `else { 69 return new Promise((resolve, reject) => { 70 resolve('[PC Preview] unknow boolean'); 71 }) 72 }`; 73 } 74 } 75 methodSignatureBody += '},\n'; 76 return methodSignatureBody; 77} 78