Refactor GraphQL schema and format JSON output

This commit is contained in:
2023-11-20 08:51:07 +08:00
parent 5075515e37
commit a22c4e8bf6
2 changed files with 69 additions and 25 deletions

View File

@@ -197,7 +197,8 @@ func main() {
http.Error(w, result.Errors[0].Error(), 500) http.Error(w, result.Errors[0].Error(), 500)
return return
} }
rJSON, _ := json.Marshal(result) // 格式化输出
rJSON, _ := json.MarshalIndent(result, "", " ")
fmt.Printf("%s \n", rJSON) fmt.Printf("%s \n", rJSON)
w.Write(rJSON) w.Write(rJSON)
}) })

View File

@@ -49,8 +49,7 @@ func NewSchema() (graphql.Schema, error) {
}, },
} }
images := &graphql.Field{ image := graphql.NewObject(graphql.ObjectConfig{
Type: graphql.NewList(graphql.NewObject(graphql.ObjectConfig{
Name: "Image", Name: "Image",
Fields: graphql.Fields{ Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.Int}, "id": &graphql.Field{Type: graphql.Int},
@@ -63,17 +62,61 @@ func NewSchema() (graphql.Schema, error) {
"create_time": &graphql.Field{Type: graphql.DateTime}, "create_time": &graphql.Field{Type: graphql.DateTime},
"update_time": &graphql.Field{Type: graphql.DateTime}, "update_time": &graphql.Field{Type: graphql.DateTime},
"user": &graphql.Field{ "user": &graphql.Field{
Type: graphql.NewObject(graphql.ObjectConfig{ Type: user,
Name: "User",
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.Int},
"nickname": &graphql.Field{Type: graphql.String},
"avatar": &graphql.Field{Type: graphql.String},
},
}),
}, },
}, },
})), })
images := &graphql.Field{
Type: graphql.NewList(image),
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{
Type: graphql.Int,
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
fmt.Println("p.Args:", p.Args)
return []interface{}{
map[string]interface{}{
"id": 1,
"width": 100,
"height": 100,
"content": "content",
"article_category_top_id": 1,
"praise_count": 1,
"collect_count": 1,
"create_time": "2018-01-01 00:00:00",
"update_time": "2018-01-01 00:00:00",
"user": map[string]interface{}{
"id": 1,
"name": "user1",
"age": 10,
"info": "info",
"price": 1.1,
"avatar": "",
},
},
map[string]interface{}{
"id": 2,
"width": 100,
"height": 100,
"content": "content",
"article_category_top_id": 1,
"praise_count": 1,
"collect_count": 1,
"create_time": "2018-01-01 00:00:00",
"update_time": "2018-01-01 00:00:00",
"user": map[string]interface{}{
"id": 2,
"name": "user2",
"age": 20,
"info": "info",
"price": 2.2,
"avatar": "",
},
},
}, nil
},
} }
rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: graphql.Fields{ rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: graphql.Fields{