GraphQL:如何处理在其自己的类型定义中引用类型? [英] GraphQL: How to handle referencing a type within its own type definition?

查看:52
本文介绍了GraphQL:如何处理在其自己的类型定义中引用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下内容:

type User {
  id: Int!
  name: String
  dob: String
  friends: [User]
}

Query {
  user(id: Int!): User
}

在我看来,我刚刚创造了无限递归的潜力:

Looks to me like I just created the potential for infinite recursion:

query GetUser($userId: Int!) {
  user(id: $userId) {
    friends {
      name
      friends {
        name
        friends {
          name
          ...etc
        }
      }
    }

  }
}

我如何在我的 user 解析器中防止这种情况发生?

How would I guard against this is in my user resolver?

推荐答案

这可能是一个潜在的问题,但您可以使用自定义验证来阻止此类请求,例如https://github.com/stems/graphql-depth-limit

This could be a potential problem, but you can use custom validation to prevent those kind of requests, e.g. https://github.com/stems/graphql-depth-limit

import depthLimit from 'graphql-depth-limit'
import express from 'express'
import graphqlHTTP from 'express-graphql'
import schema from './schema'

const app = express()

app.use('/graphql', graphqlHTTP((req, res) => ({
  schema,
  validationRules: [ depthLimit(10) ]
})))

这篇关于GraphQL:如何处理在其自己的类型定义中引用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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