jjzjj

go - 获取变量\"$address\"不能是非输入类型\"String!\in go-graphql

coder 2024-07-06 原文

我已经使用 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 - 获取变量\"$address\"不能是非输入类型\"String!\in go-graphql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53916845/

有关go - 获取变量\"$address\"不能是非输入类型\"String!\in go-graphql的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  4. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  5. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  6. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  7. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  8. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  9. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  10. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

随机推荐