当前位置:首页 > 文章列表 > Golang > Go问答 > 在 go-graphql 中设置变量“$address”为非输入类型“String!”是不允许的

在 go-graphql 中设置变量“$address”为非输入类型“String!”是不允许的

来源:stackoverflow 2024-03-20 14:18:30 0浏览 收藏

在 Go 中使用 graphql-go 库时,为 GraphQL 查询设置查询参数可能导致错误。当直接传递参数时,查询可以正常工作,但使用查询参数时却会失败。这可能是由于架构中重复的类型名称造成的。为了解决此问题,建议重命名其中一个重复的类型名称,以消除歧义。

问题内容

我已经使用 graphql-go 库在 go 中成功设置了 graphql 服务器。但是,当我在进行查询时传递查询参数时,似乎出现错误。因此,我有一个名为 emails 的查询,它以 address 作为参数,并查询数据库以返回与给定 address 关联的所有电子邮件的结果。当我直接传递 address 参数时,一切似乎都运行良好,正如您从此图中看到的那样:

但是,当我向它传递查询参数时,它似乎不起作用,如下所示:

我不认为这两个语句应该给出相同的结果。然而,情况似乎并非如此。有人可以帮助我理解为什么我会收到这些错误吗?这是我的代码

package main

import (
    "log"
    "net/http"

    "github.com/graphql-go/graphql"
    "github.com/graphql-go/handler"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/credentials"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)

var sess, _ = session.NewSession()

// Email - Used to represent a single email object stored in
// dynamodb. Fields 'attachments', 'body-html', 'stripped-html' and
// 'stripped-text' may be empty.
type Email struct {
    To           string   `json:"to"`
    Recipients   []string `json:"recipients"`
    Token        string   `json:"token"`
    Sender       string   `json:"sender"`
    Subject      string   `json:"subject"`
    Timestamp    string   `json:"timestamp"`
    Attachments  []string `json:"attachments"`
    Mime         string   `json:"mime"`
    BodyPlain    string   `json:"body_plain"`
    BodyHTML     string   `json:"body_html"`
    StrippedText string   `json:"stripped_text"`
    StrippedHTML string   `json:"stripped_html"`
}

// emailType - a new graphql object representing a single email
var emailType = graphql.NewObject(graphql.ObjectConfig{
    Name: "Email",
    Fields: graphql.Fields{
        "to": &graphql.Field{
            Type: graphql.String,
        },
        "recipients": &graphql.Field{
            Type: graphql.NewList(graphql.String),
        },
        "token": &graphql.Field{
            Type: graphql.String,
        },
        "sender": &graphql.Field{
            Type: graphql.String,
        },
        "subject": &graphql.Field{
            Type: graphql.String,
        },
        "attachments": &graphql.Field{
            Type: graphql.NewList(graphql.String),
        },
        "timestamp": &graphql.Field{
            Type: graphql.String,
        },
        "mime": &graphql.Field{
            Type: graphql.String,
        },
        "body_plain": &graphql.Field{
            Type: graphql.String,
        },
        "body_html": &graphql.Field{
            Type: graphql.String,
        },
        "stripped_text": &graphql.Field{
            Type: graphql.String,
        },
        "stripped_html": &graphql.Field{
            Type: graphql.String,
        },
    },
})

// emailType - a new graphql object representing a deleted email.
var deleteEmailType = graphql.NewObject(graphql.ObjectConfig{
    Name: "Email",
    Fields: graphql.Fields{
        "to": &graphql.Field{
            Type: graphql.String,
        },
        "token": &graphql.Field{
            Type: graphql.String,
        },
    },
})

func disableCors(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "*")
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        w.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, Content-Length, Accept-Encoding")

        // I added this for another handler of mine,
        // but I do not think this is necessary for GraphQL's handler
        if r.Method == "OPTIONS" {
            w.Header().Set("Access-Control-Max-Age", "86400")
            w.WriteHeader(http.StatusOK)
            return
        }

        h.ServeHTTP(w, r)
    })
}

func main() {
    // configures the rootQuery for the graphQL API
    rootQuery := graphql.NewObject(graphql.ObjectConfig{
        Name: "Query",
        Fields: graphql.Fields{
            "emails": &graphql.Field{
                Type: graphql.NewList(emailType),
                Args: graphql.FieldConfigArgument{
                    "address": &graphql.ArgumentConfig{
                        Type: graphql.String,
                    },
                },
                Resolve: func(params graphql.ResolveParams) (interface{}, error) {
                    address := params.Args["address"].(string)
                    svc := dynamodb.New(sess)
                    result, err := svc.Query(&dynamodb.QueryInput{
                        TableName: aws.String("emails_db"),
                        KeyConditions: map[string]*dynamodb.Condition{
                            "to": {
                                ComparisonOperator: aws.String("EQ"),
                                AttributeValueList: []*dynamodb.AttributeValue{
                                    {
                                        S: aws.String(address),
                                    },
                                },
                            },
                        },
                    })
                    if err != nil {
                        return nil, nil
                    }

                    // unmarshalls all the emails to recs
                    recs := []Email{}
                    err = dynamodbattribute.UnmarshalListOfMaps(result.Items, &recs)
                    if err != nil {
                        return nil, nil
                    }
                    return recs, nil
                },
            },
        },
    })

    // configures the rootMutation for the graphQL API
    rootMutation := graphql.NewObject(graphql.ObjectConfig{
        Name: "Mutation",
        Fields: graphql.Fields{
            "email": &graphql.Field{
                Type: deleteEmailType,
                Args: graphql.FieldConfigArgument{
                    "address": &graphql.ArgumentConfig{
                        Type: graphql.NewNonNull(graphql.String),
                    },
                    "token": &graphql.ArgumentConfig{
                        Type: graphql.NewNonNull(graphql.String),
                    },
                },
                Resolve: func(params graphql.ResolveParams) (interface{}, error) {
                    address := params.Args["address"].(string)
                    token := params.Args["token"].(string)
                    svc := dynamodb.New(sess)
                    _, err := svc.DeleteItem(&dynamodb.DeleteItemInput{
                        TableName: aws.String("emails_db"),
                        Key: map[string]*dynamodb.AttributeValue{
                            "to": {
                                S: aws.String(address),
                            },
                            "token": {
                                S: aws.String(token),
                            },
                        },
                    })
                    if err != nil {
                        return nil, err
                    }

                    // unmarshalls all the emails to recs
                    rec := Email{To: address, Token: token}
                    return rec, nil
                },
            },
        },
    })

    // configures routes
    schema, _ := graphql.NewSchema(graphql.SchemaConfig{
        Mutation: rootMutation,
        Query:    rootQuery,
    })
    h := handler.New(&handler.Config{
        Schema:   &schema,
        Pretty:   true,
        GraphiQL: true,
    })
    http.Handle("/graphql", disableCors(h))
    log.Fatal(http.ListenAndServe(":80", nil))
}

解决方案


从您看到的错误消息中尚不清楚,但这可能是由于架构中的重复名称所致,如 this Github issue 中所述。您有两种名为 Email 的类型 - emailTypedeleteEmailType。尝试重命名其中一个。

以上就是《在 go-graphql 中设置变量“$address”为非输入类型“String!”是不允许的》的详细内容,更多关于的资料请关注golang学习网公众号!

版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
无法通过独立的 Go 应用程序访问 GCP 的秘密管理器无法通过独立的 Go 应用程序访问 GCP 的秘密管理器
上一篇
无法通过独立的 Go 应用程序访问 GCP 的秘密管理器
更换硬盘的墨尔本mac服务
下一篇
更换硬盘的墨尔本mac服务
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 笔灵AI生成答辩PPT:高效制作学术与职场PPT的利器
    笔灵AI生成答辩PPT
    探索笔灵AI生成答辩PPT的强大功能,快速制作高质量答辩PPT。精准内容提取、多样模板匹配、数据可视化、配套自述稿生成,让您的学术和职场展示更加专业与高效。
    23次使用
  • 知网AIGC检测服务系统:精准识别学术文本中的AI生成内容
    知网AIGC检测服务系统
    知网AIGC检测服务系统,专注于检测学术文本中的疑似AI生成内容。依托知网海量高质量文献资源,结合先进的“知识增强AIGC检测技术”,系统能够从语言模式和语义逻辑两方面精准识别AI生成内容,适用于学术研究、教育和企业领域,确保文本的真实性和原创性。
    35次使用
  • AIGC检测服务:AIbiye助力确保论文原创性
    AIGC检测-Aibiye
    AIbiye官网推出的AIGC检测服务,专注于检测ChatGPT、Gemini、Claude等AIGC工具生成的文本,帮助用户确保论文的原创性和学术规范。支持txt和doc(x)格式,检测范围为论文正文,提供高准确性和便捷的用户体验。
    37次使用
  • 易笔AI论文平台:快速生成高质量学术论文的利器
    易笔AI论文
    易笔AI论文平台提供自动写作、格式校对、查重检测等功能,支持多种学术领域的论文生成。价格优惠,界面友好,操作简便,适用于学术研究者、学生及论文辅导机构。
    47次使用
  • 笔启AI论文写作平台:多类型论文生成与多语言支持
    笔启AI论文写作平台
    笔启AI论文写作平台提供多类型论文生成服务,支持多语言写作,满足学术研究者、学生和职场人士的需求。平台采用AI 4.0版本,确保论文质量和原创性,并提供查重保障和隐私保护。
    40次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码