在Go中创建循环GraphQL类型

时间:2020-05-26 21:38:21

标签: go graphql

我正在尝试创建两个GraphQL类型,即Item和Listing,它们包含彼此的实例作为字段。在GraphQL类型语言中,它们将是:

type Item {
    id: ID!
    name: String!
    ...
    listings: [Listing]!
}

type Listing {
    id: ID!
    price: Int!
    ...
    item: Item!
}

(...表示无关的省略字段)

我已经看到其他项目可以做到这一点,所以我知道这是可能的,但是我很难用github.com/graphql-go/graphql来做到这一点。根据我在网上学到的信息,使用Go可以做到这一点:

var ItemType graphql.Type = graphql.NewObject(
    graphql.ObjectConfig {
        Name: "Item",
        Fields: graphql.Fields {
            "id": &graphql.Field {
                Type: graphql.ID,
             },
             "name": &graphql.Field {
                Type: graphql.String,
             },
             ...
             "listings": &graphql.Field {
                Type: graphql.NewList(ListingType),
             },
        },
    },
)

var ListingType graphql.Type = graphql.NewObject(
    graphql.ObjectConfig {
        Name: "Listing",
        Fields: graphql.Fields {
            "id": &graphql.Field {
                Type: graphql.ID,
             },
             "price": &graphql.Field {
                Type: graphql.Int,
             },
             ...
             "item": &graphql.Field {
                Type: ItemType,
             },
        },
    },
)

但这会导致初始化循环:

./test.go:9:5: initialization loop:
        /home/william/Desktop/test.go:9:5: ItemType refers to
        /home/william/Desktop/test.go:26:5: ListingType refers to
        /home/william/Desktop/test.go:9:5: ItemType

我知道发生这种情况是因为编译器需要知道ItemType的大小才能确定ListingType的大小才能确定ItemType的大小(等等),但是我不确定绕开它。

1 个答案:

答案 0 :(得分:1)

recommended way正在使用this.http.setSSLCertMode('pinned'); this.http.setDataSerializer('utf8');

HttpInterceptor