Skip to content

Commit

Permalink
fix(graphql): get number of arguments util
Browse files Browse the repository at this point in the history
ensure getNumberOfArguments returns the correct number of arguments for functions with body that use parenthesis.
  • Loading branch information
thiagomini committed Oct 25, 2022
1 parent 8ba6180 commit 93cbbd7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
19 changes: 15 additions & 4 deletions packages/graphql/lib/utils/get-number-of-arguments.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,20 @@
*/
export function getNumberOfArguments(fn: Function): number | undefined {
// Removing newlines is necessary to use easier regex and handle multi-line functions
const functionAsStringWithouNewLines = fn.toString().replace(/\n/g, '');
const functionAsStringWithoutNewLines = fn.toString().replace(/\n/g, '');

const anythingEnclosedInParenthesesRegex = /\(.+\)/;
/* The RegExp below uses a non-greedy match (the question mark), meaning that it tries to find
* the smallest possible match. This ensures that we don't accidentally
* consider the function's body as part of the regex match, since we aim
* to get only the parameters section.
*/
const anythingEnclosedInParenthesesRegex = /\(.*?\)/;

const regexMatchedArray = functionAsStringWithouNewLines.match(
const regexMatchedArray = functionAsStringWithoutNewLines.match(
new RegExp(anythingEnclosedInParenthesesRegex),
);

if (regexMatchedArray) {
if (functionHasOneOrMoreArguments(regexMatchedArray)) {
const functionParametersAsString = regexMatchedArray[0];

// Removing arrays and objects is also necessary because we count the number of commas in the string,
Expand All @@ -30,3 +35,9 @@ export function getNumberOfArguments(fn: Function): number | undefined {

return 0;
}

function functionHasOneOrMoreArguments(
functionRegexMatchArray: RegExpMatchArray,
) {
return functionRegexMatchArray && functionRegexMatchArray[0] !== '()';
}
11 changes: 11 additions & 0 deletions packages/graphql/tests/utils/get-number-of-arguments.util.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ describe('getNumberOfArguments', () => {
expect(getNumberOfArguments(zeroArgFunction)).toBe(0);
});

it('should return 0 for a 0-argument function with body', () => {
function zeroArgFunction() {
if (1 == +'2') {
return false;
}

return true;
}
expect(getNumberOfArguments(zeroArgFunction)).toBe(0);
});

it('should return 1 for a 1-argument function', () => {
function oneArgFunction(_arg1: any) {}
expect(getNumberOfArguments(oneArgFunction)).toBe(1);
Expand Down

0 comments on commit 93cbbd7

Please sign in to comment.