如何将GraphQL请求字符串解析为对象 [英] How to parse GraphQL request string into an object

查看:276
本文介绍了如何将GraphQL请求字符串解析为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为GraphQL运行Apollo lambda服务器.我想从POST请求主体中截获GraphQL查询/变异并对其进行解析,以便我可以找出请求所要求的查询/变异.环境是Node.js.

I am running Apollo lambda server for GraphQL. I want to intercept the GraphQL query/mutation from the POST request body and parse it so I can find out which query/mutation the request is asking for. The environment is Node.js.

该请求不是JSON,而是GraphQL查询语言.我四处张望,试图找到一种方法将其解析为可以导航的对象,但我正在绘制空白.

The request isn't JSON, it's GraphQL query language. I've looked around to try and find a way to parse this into an object that I can navigate but I'm drawing a blank.

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

The Apollo server must be parsing it somehow to direct the request. Does anyone know a library that will do this or pointers on how I can parse the request? Examples of request bodies and what I want to retrieve below.

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

我想确定这是一个查询,并且正在询问qQueryEndpoint.

I would like to identify that this is a query and that qQueryEndpoint is being asked for.

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

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

I would like to identify that this is a mutation and the saveSomething mutation is being used.

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

My first idea for this is to strip out the line breaks and try and use regular expressions to parse the request but it feels like a very brittle solution.

推荐答案

您可以使用 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

这篇关于如何将GraphQL请求字符串解析为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆