Home > database >  Capturing graphql data key between the first opening curly bracket and the second opening parenthesi
Capturing graphql data key between the first opening curly bracket and the second opening parenthesi

Time:11-14

I am trying to write a regex in an effort to refactor some end-to-end tests on a GraphQL API.

Here are some example of what I'd like to capture:

query SignIn($payload: AuthCredentialsInput!) {
  signIn(payload: $payload) {
    token
  }
}

Should retrieve signIn

mutation SendConfirmationEmail($athleteId: ID!) {
  sendConfirmationEmail(athleteId: $athleteId) {
    id
  }
}

Should retrieve sendConfirmationEmail

mutation CreateProgram($title: String!) {
  createProgram(title: $title) {
    id
    title
  }
}

Should retrieve createProgram

query GetAllExerciseTemplates {
  getAllExerciseTemplates {
    id
    title
  }
}

Should retrieve getAllExerciseTemplates

At the moment I need to pass those key by hand for every end-to-end test.

My best attempt is this regex: . ?\{ [ \r\n\t\f\v ](. )\(

    const regexTest = query.query.match(/. ?\{ [ \r\n\t\f\v ](. )\(/)
    console.warn(regexTest)

But the result is this:

  console.warn
    [
      'mutation CreateProgram($title: String!) {\n          createProgram(',
      '          createProgram',
      index: 0,
      input: 'mutation CreateProgram($title: String!) {\n'  
        '          createProgram(title: $title) {\n'  
        '            id\n'  
        '            title\n'  
        '          }\n'  
        '        }',
      groups: undefined
    ]

Any regex expert that can solve it here?

EDIT : Here is the best shot I did, yet it could be great if I could have only one regex instead of two

function getDataKey(query: Query) {
  const keyBeforeFirstParenthesis = /. ?{[\r\n\t\f\v ] (. )\(/
  const keyBeforeFirstBracket = /. ?{[\r\n\t\f\v ] (. ) {/

  let regExpMatchArray
  regExpMatchArray = query.query.match(keyBeforeFirstParenthesis)
  if (!regExpMatchArray)
    regExpMatchArray = query.query.match(keyBeforeFirstBracket)

  return regExpMatchArray[1]
}

CodePudding user response:

You can join the two regexps into

/. ?{\s*(. ?)\s*[({]/

See the regex demo. Details:

  • . ? - one or more chars other than line break chars as few as possible
  • { - a { char
  • \s* - zero or more whitespaces
  • (. ?) - Group 1: one or more chars other than line break chars as few as possible
  • \s* - zero or more whitespaces
  • [({] - ( or { char.
  • Related