我正在编写授权组件来验证GraphQL查询。
使用ValidationContext
对象,我设法获取操作类型(变异/查询),操作名称和查询中包含的非标量字段名称。
我需要的是获取这些非标量字段的GraphQL类型。
以下是我用于验证器的代码(使用Typescript):
let entitiesArray:Array<string> = new Array<string>()
function getRecursiveSelectionSetNodes (selSetNode:SelectionSetNode) {
selSetNode.selections.forEach ((node:FieldNode, index, array) => {
if (node.selectionSet) {
entitiesArray.push(node.name.value) // I could push the whole node, and make an array of nodes if necessary
getRecursiveSelectionSetNodes (node.selectionSet)
}
})
}
export const authorizeQuery = function authorizeQuery (context: ValidationContext): any {
let opNode:OperationDefinitionNode = getOperationAST(context.getDocument())
let opType = opNode.operation
console.log ('_________________ AUTH OPERATION TYPE: ', opType)
let opFieldNode:FieldNode = <FieldNode>opNode.selectionSet.selections[0]
let opName = opFieldNode.name.value
console.log ('_________________ AUTH OPERATION NAME: ', opName)
let selSetUser:SelectionSetNode = opFieldNode.selectionSet
// Selected fields by the user
// Here, first-level nodes will be objects requested by the query
// The nodes without a nested "SelectionSet" node will be scalar
// Nodes with a nested "SelectionSet" are non-scalar that need to be checked
getRecursiveSelectionSetNodes (selSetUser)
console.log ('_________________ AUTH ENTITIES: ', JSON.stringify(entitiesArray))
return []
}
此代码返回字段名称,而不是类型,因此我需要映射字段名称&#34; users&#34;使用graphQL类型&#34; User []&#34;等等,所以我可以根据请求的graphql类型执行授权。
有什么想法吗?