首页 文章

如何将GraphQL请求字符串解析为对象

提问于
浏览
4

我正在为GraphQL运行Apollo lambda服务器 . 我想拦截来自POST请求体的GraphQL查询/变异并解析它,以便我可以找出请求要求的查询/变异 . 环境是Node.js.

请求不是JSON,它是GraphQL查询语言 . 我环顾四周试图找到一种方法将其解析成一个我可以导航的对象,但我正在画一个空白 .

Apollo服务器必须以某种方式解析它以指导请求 . 有没有人知道这样做的库或指向我如何解析请求的指针?请求正文的示例以及我想在下面检索的内容 .

{"query":"{\n  qQueryEndpoint {\n    id\n  }\n}","variables":null,"operationName":null}

我想确定这是一个查询,并且要求 qQueryEndpoint .

{"query":"mutation {\\n  saveSomething {\\n    id\\n  }\\n}","variables":null}

我想确定这是一个突变,正在使用 saveSomething 突变 .

我的第一个想法是删除换行符并尝试使用正则表达式来解析请求,但这感觉就像一个非常脆弱的解决方案 .

1 回答

  • 7

    你可以使用graphql-tag

    const gql = require('graphql-tag');
    
    const query = `
      {
        qQueryEndpoint {
          id
        }
      }
    `;
    
    const obj = gql`
      ${query}
    `;
    
    console.log('operation', obj.definitions[0].operation);
    console.log('name', obj.definitions[0].selectionSet.selections[0].name.value);
    

    打印出来:

    operation query
    name qQueryEndpoint
    

    随着你的突变:

    operation mutation
    name saveSomething
    

相关问题