如何将 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