图QL 深度限制
叉子从 图QL 深度限制
死而复生地防御无限制的GraphQL查询. 仅通过查询限制查询的复杂性 深度。 。 。 .
为什么?
如果你有一个 Album 类型有列表 Song编号.
{
album(id: 42) {
songs {
title
artists
}
}
}
或许你有一个不同的切入点 Song 类型允许您返回 Album。 。 。 .
{
song(id: 1337) {
title
album {
title
}
}
}
这让你的服务器打开了周期性查询的可能性!
query evil {
album(id: 42) {
songs {
album {
songs {
album {
songs {
album {
songs {
album {
songs {
album {
songs {
album {
# and so on...
}
}
}
}
}
}
}
}
}
}
}
}
}
}
如果查询深度为一万, 您的服务器将如何处理 ? 这可能会成为一个非常昂贵的操作,在某个时候将CPU钉入服务器或数据库. 这可能是监督事务司的脆弱性. 我们想要一种方法来验证收到的询问的复杂性.
此执行允许您限制 总深度 每个操作.
量化复杂性
准确决定 何时 a GraphQL 查询“太复杂”是一种细微而微妙的艺术. 感觉有点像决定需要多少粒砂来作"一叠砂". 其他一些库有开发者指定 费用 ,并添加每个查询的累计费用.
图克l-验证-复杂 以 类型, (中文(简体) ), 财务报告和审定财务报表 图克-克-复杂度 是否基于每个 字段。 。 。 .
增加成本可能对某些后端有效,但并不总是忠实地代表复杂性.
通过增加每个深度的成本,就好像复杂度随着深度的增大而呈线性增长.
有时复杂程度会增加 指数 深处,例如如果请求一个字段意味着做另一个 SQL JOIN。 。 。 .
此库验证了查询(和突变)的总深度.
下面是一些深度为0的查询
# simplest possible query
query shallow1 {
thing1
}
# inline fragments don't actually increase the depth
query shallow2 {
thing1
... on Query {
thing2
}
}
# neither do named fragments
query shallow3 {
...queryFragment
}
fragment queryFragment on Query {
thing1
}
更深的查询
# depth = 1
query deep1_1 {
viewer {
name
}
}
query deep1_2 {
viewer {
... on User {
name
}
}
}
# depth = 2
query deep2 {
viewer {
albums {
title
}
}
}
# depth = 3
query deep3 {
viewer {
albums {
...musicInfo
songs{
...musicInfo
}
}
}
}
fragment musicInfo on Music {
id
title
artists
}
使用量
$ npm install @cungminh2710/graphql-depth-limit
和我们一起工作 表达式ql 财务报告和审定财务报表 地图。 。 。 . 以下是快递公司的例子.
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) ]
})))
第一个论点是总深度限制。 这将为询问(或突变)扔出一个验证错误,其深度为11个或更多.
第二个参数是一个选项对象,您可以在此指定被忽略的字段。 反省字段默认被忽略.
第三个论点是: Object 它是一个每个操作深度的地图.
depthLimit(
10,
{ ignore: [ /_trusted$/, 'idontcare' ] },
depths => console.log(depths)
)
现在之前的邪恶查询会告诉客户:
{
"errors": [
{
"message": "'evil' exceeds maximum operation depth of 10",
"locations": [
{
"line": 13,
"column": 25
}
]
}
]
}
未来工作
- 类型特定子深度限制,例如,您只能从一个
Album类型,从User类型等. - 更多定制选项, 如自定义错误 .
文档
深度( 最大深度 , [选项] , [召回]) QQ function
为 GraphQL 查询深度创建验证符
仁爱:全球职能
回返数字 : function - GraphQL 验证阶段的验证器功能.
| 参数 | 类型 | 说明 |
|---|---|---|
| 最大深度 | Number | GraphQL 文档中任何操作的最大允许深度 . |
| [可选 | Object | |
| 选项 | String | RegExp | function | 停止基于字段名的递归深度检查。 或匹配名称的字符串或 regexp, 或返回布尔函数 . |
| [召回] | function | 每次验证运行时都会调用. 接收每个操作深度的映射对象. |