Skip to content

Commit

Permalink
Merge pull request #23 from snyk-tech-services/develop
Browse files Browse the repository at this point in the history
Release
  • Loading branch information
lili2311 authored Jan 18, 2021
2 parents 043f9e0 + 60e6e24 commit 9a470b0
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 30 deletions.
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
node_modules/
npm-debug.log
.npmrc
# output
dist
.DS_Store
Expand All @@ -14,4 +13,4 @@ snyk.json
snyk-prepared.json
*.bak
test/fixtures/*.json
test/lib/*.test.ts
test/lib/*.test.ts
2 changes: 2 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
package-lock=false

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,13 @@
"@snyk/configstore": "^3.2.0-rc1",
"@types/lodash": "^4.14.155",
"@types/node": "^14.0.12",
"axios": "^0.19.2",
"axios": "^0.21.1",
"debug": "^4.1.1",
"jsonq": "^1.2.0",
"lodash": "^4.17.15",
"snyk": "^1.360.0",
"snyk-config": "^3.0.0",
"snyk-request-manager": "^1.1.0",
"snyk-config": "^4.0.0",
"snyk-request-manager": "1.3.1",
"source-map-support": "^0.5.16",
"tslib": "^1.10.0",
"typescript": "^3.9.5"
Expand Down
67 changes: 50 additions & 17 deletions src/lib/generators/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ interface PreparedMethod {
name: string;
argsList: Array<string>;
qsList?: Array<string>;
paramList?: Array<string>;
url: string;
response?: Response;
}
Expand Down Expand Up @@ -80,11 +81,11 @@ const generateClass = (
isRootClass,
)}
${generateConstructors(classToGenerate, parentClassType, isRootClass)}
${generateMethods(classToGenerate)}
}
${generateSubClasses(classToGenerate, isRootClass)}
`;
Expand Down Expand Up @@ -203,7 +204,7 @@ const generateResponseInterfaces = (
} {
header: ${method.response.header}
}
`;
break;
case 'bodyless':
Expand Down Expand Up @@ -268,7 +269,7 @@ const generateSubClasses = (
if (subClassArray) {
subClassArray.forEach((subClass) => {
codeToReturn += `${generateClass(subClass, classType, false)}
`;
});
}
Expand All @@ -293,7 +294,7 @@ const generateConstructors = (
if (!isRootClass) {
constructorsDeclaration.push(`parentContext: Object`);
constructorsParameters += `
const properties = Object.getOwnPropertyNames(parentContext)
properties.forEach(property => {
Object(this.currentContext)[property] = Object(parentContext)[property]
Expand All @@ -306,14 +307,30 @@ const generateConstructors = (
`;
}
let noInterface: boolean = false;
let optionalConstructorParam: string = '';
if (
classToGenerateConstructorsFor.methods &&
classToGenerateConstructorsFor.methods.length > 0
) {
if (
classToGenerateConstructorsFor.methods.some(
(method) => method.params.length == 0,
)
) {
// the root class constructor argument should therefore be optional
// as there might be methods not needing it (POST /org for example)
optionalConstructorParam = '?';
}
}

if (
classToGenerateConstructorsFor.param &&
classToGenerateConstructorsFor.param.filter((x) => x).length > 0
) {
constructorsDeclaration.push(
`${utils.formatClassName(
classToGenerateConstructorsFor.name,
)}param:${utils
)}param${optionalConstructorParam}:${utils
.formatClassName(classToGenerateConstructorsFor.name)
.toLowerCase()}Class`,
);
Expand All @@ -338,7 +355,9 @@ const generateConstructors = (
parameter,
)} = ${utils.formatClassName(
classToGenerateConstructorsFor.name,
)}param.${utils.removeCurlyBraces(parameter)} || ${defaultValue}
)}param${optionalConstructorParam}.${utils.removeCurlyBraces(
parameter,
)} || ${defaultValue}
`;
}
});
Expand Down Expand Up @@ -429,11 +448,11 @@ const generateMethods = (classToGenerateMethodsFor: ConsolidatedClass) => {

const currentMethod: PreparedMethod = {
name: method.verb,
paramList: paramsCode,
argsList: argsList,
url: urlForPreparedMethod,
response: method.response,
};

if (methodsMap.has(method.verb)) {
let paramList = _.uniq(method.params.concat(method.qsParams));
let url = method.url;
Expand All @@ -442,8 +461,13 @@ const generateMethods = (classToGenerateMethodsFor: ConsolidatedClass) => {
let existingUrl = methodsMap.get(method.verb)?.url;

let finalMethodParamList: string[] = [];

if (existingMethodParamList.length > paramList.length) {
if (existingMethodParamList.length == 0 && paramList.length == 0) {
// Just passing through if no parameters but only different values in the path
// so far only /user/{usedId}, with userId=me being a special case called out
// in other words, userId being 'me' or another value if handled in the class constructor
// so no need to tweak the url
url = `${existingUrl}`;
} else if (existingMethodParamList.length > paramList.length) {
finalMethodParamList = existingMethodParamList;
const paramListDifference = _.difference(
existingMethodParamList,
Expand Down Expand Up @@ -501,6 +525,7 @@ const generateMethods = (classToGenerateMethodsFor: ConsolidatedClass) => {
const url = `${currentMethod.url}`;
const updatedMethod: PreparedMethod = {
name: method.verb,
paramList: currentMethod.paramList,
argsList: currentMethod.argsList,
url: url,
response: currentMethod.response,
Expand All @@ -527,10 +552,19 @@ const generateMethods = (classToGenerateMethodsFor: ConsolidatedClass) => {
let qsIfStatements = '';
qsParametersNamesList.forEach((qsParameterName) => {
qsIfStatements += `
if(${qsParameterName}){
if(${qsParameterName}){
urlQueryParams.push('${qsParameterName}='+${qsParameterName})
}\n`;
});

let emptyBodyNeeded = false;
if (
(method.name == 'post' || method.name == 'put') &&
!method.argsList.map((x) => x.split(':')[0]).includes('body')
) {
emptyBodyNeeded = true;
}

codeToReturn += `
async ${method.name} (${method.argsList}):${
method.response?.type == 'bodyless'
Expand All @@ -547,25 +581,25 @@ const generateMethods = (classToGenerateMethodsFor: ConsolidatedClass) => {
if(urlQueryParams.length > 0){
url += \`?\${urlQueryParams.join("&")}\`
}
try {
const result = await requestManager.request({verb: '${
method.name
}', url: url ${
method.argsList.map((x) => x.split(':')[0]).includes('body')
? ',body : JSON.stringify(body)'
: ''
: `${emptyBodyNeeded ? ', body: JSON.stringify({})' : ''}`
}})
if(!Object(this.currentContext)['fullResponse'] && result.data){
return result.data
} else {
return result
}
} catch (err) {
throw new ClientError(err)
}
}
`;
});
Expand All @@ -588,7 +622,6 @@ import { requestsManager } from 'snyk-request-manager'
const requestManager = new requestsManager(${requestManagerSettings})
`;
console.log('fdfd')

parsedJSON.forEach((classItem) => {
fs.writeFileSync(
Expand Down
25 changes: 17 additions & 8 deletions src/lib/generators/generateTestCases.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,10 @@ const extractCommandDetailsFromClass = (
});
});

if (method.verb == 'put' || method.verb == 'post') {
if (
(method.verb == 'put' || method.verb == 'post') &&
!_.isEmpty(method.body)
) {
listOfParams.unshift('body');
}

Expand Down Expand Up @@ -293,13 +296,13 @@ const generateTestFile = (
};
`;

if (commandMethod == 'put' || commandMethod == 'post') {
// extract the namespace(s) from command after the first class instantiation
const bodyType = extractBodyTypeFromCommand(command[0]);
// if (commandMethod == 'put' || commandMethod == 'post') {
// // extract the namespace(s) from command after the first class instantiation
// const bodyType = extractBodyTypeFromCommand(command[0]);

// codeToReturn += `const body: ${bodyType} = {body:fixtures.request.body.${commandCoordinates.join('.')}}
// `;
}
// // codeToReturn += `const body: ${bodyType} = {body:fixtures.request.body.${commandCoordinates.join('.')}}
// // `;
// }
let url = command[1].replace(/{/g, '${fixtures.request.');

if (
Expand Down Expand Up @@ -339,7 +342,13 @@ const generateTestFile = (
mockAxios.mockResponseFor({url: \`${url}\`},axiosResponse);
expect(mockAxios.${commandMethod}).toHaveBeenCalledWith(\`${url}\`${
body.join() == '' ? '' : ', JSON.stringify(' + body.join() + ')'
body.join() == ''
? `${
commandMethod == 'post' || commandMethod == 'put'
? ',JSON.stringify({})'
: ''
}`
: ', JSON.stringify(' + body.join() + ')'
})
Expand Down

0 comments on commit 9a470b0

Please sign in to comment.