本文整理汇总了Golang中github.com/graphql-go/graphql.Do函数的典型用法代码示例。如果您正苦于以下问题:Golang Do函数的具体用法?Golang Do怎么用?Golang Do使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Do函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestPluralIdentifyingRootField_AllowsFetching
func TestPluralIdentifyingRootField_AllowsFetching(t *testing.T) {
query := `{
usernames(usernames:["dschafer", "leebyron", "schrockn"]) {
username
url
}
}`
expected := &graphql.Result{
Data: map[string]interface{}{
"usernames": []interface{}{
map[string]interface{}{
"username": "dschafer",
"url": "www.facebook.com/dschafer",
},
map[string]interface{}{
"username": "leebyron",
"url": "www.facebook.com/leebyron",
},
map[string]interface{}{
"username": "schrockn",
"url": "www.facebook.com/schrockn",
},
},
},
}
result := graphql.Do(graphql.Params{
Schema: pluralTestSchema,
RequestString: query,
})
if !reflect.DeepEqual(result, expected) {
t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
}
}
示例2: TestQuery_ExecutionDoesNotAddErrorsFromFieldResolveFn
func TestQuery_ExecutionDoesNotAddErrorsFromFieldResolveFn(t *testing.T) {
qError := errors.New("queryError")
q := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return nil, qError
},
},
"b": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "ok", nil
},
},
},
})
blogSchema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: q,
})
if err != nil {
t.Fatalf("unexpected error, got: %v", err)
}
query := "{ b }"
result := graphql.Do(graphql.Params{
Schema: blogSchema,
RequestString: query,
})
if len(result.Errors) != 0 {
t.Fatalf("wrong result, unexpected errors: %+v", result.Errors)
}
}
示例3: TestNodeInterfaceAndFields_AllowsRefetching_ReturnsNullForBadIDs
func TestNodeInterfaceAndFields_AllowsRefetching_ReturnsNullForBadIDs(t *testing.T) {
query := `{
node(id: "5") {
id
}
}`
expected := &graphql.Result{
Data: map[string]interface{}{
"node": nil,
},
Errors: []gqlerrors.FormattedError{
{
Message: "Unknown node",
Locations: []location.SourceLocation{},
},
},
}
result := graphql.Do(graphql.Params{
Schema: nodeTestSchema,
RequestString: query,
})
if !reflect.DeepEqual(result, expected) {
t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
}
}
示例4: TestObjectIdentification_TestFetching_CorrectlyRefetchesTheEmpire
func TestObjectIdentification_TestFetching_CorrectlyRefetchesTheEmpire(t *testing.T) {
query := `
query EmpireRefetchQuery {
node(id: "RmFjdGlvbjoy") {
id
... on Faction {
name
}
}
}
`
expected := &graphql.Result{
Data: map[string]interface{}{
"node": map[string]interface{}{
"id": "RmFjdGlvbjoy",
"name": "Galactic Empire",
},
},
}
result := graphql.Do(graphql.Params{
Schema: starwars.Schema,
RequestString: query,
})
if !reflect.DeepEqual(result, expected) {
t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
}
}
示例5: main
func main() {
// Schema
fields := graphql.Fields{
"hello": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) interface{} {
return "world"
},
},
}
rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields}
schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}
schema, err := graphql.NewSchema(schemaConfig)
if err != nil {
log.Fatalf("failed to create new schema, error: %v", err)
}
// Query
query := `
{
hello
}
`
params := graphql.Params{Schema: schema, RequestString: query}
r := graphql.Do(params)
if len(r.Errors) > 0 {
log.Fatalf("failed to execute graphql operation, errors: %+v", r.Errors)
}
rJSON, _ := json.Marshal(r)
fmt.Printf("%s \n", rJSON) // {“data”:{“hello”:”world”}}
}
示例6: TestObjectIdentification_TestFetching_CorrectlyFetchesTheIDAndTheNameOfTheRebels
func TestObjectIdentification_TestFetching_CorrectlyFetchesTheIDAndTheNameOfTheRebels(t *testing.T) {
query := `
query RebelsQuery {
rebels {
id
name
}
}
`
expected := &graphql.Result{
Data: map[string]interface{}{
"rebels": map[string]interface{}{
"id": "RmFjdGlvbjox",
"name": "Alliance to Restore the Republic",
},
},
}
result := graphql.Do(graphql.Params{
Schema: starwars.Schema,
RequestString: query,
})
if !reflect.DeepEqual(result, expected) {
t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
}
}
示例7: TestPluralIdentifyingRootField_Configuration_ArgNames_WrongArgNameSpecified
func TestPluralIdentifyingRootField_Configuration_ArgNames_WrongArgNameSpecified(t *testing.T) {
t.Skipf("Pending `validator` implementation")
query := `{
usernames(usernamesMisspelled:["dschafer", "leebyron", "schrockn"]) {
username
url
}
}`
expected := &graphql.Result{
Data: nil,
Errors: []gqlerrors.FormattedError{
gqlerrors.FormattedError{
Message: `Unknown argument "usernamesMisspelled" on field "usernames" of type "Query".`,
Locations: []location.SourceLocation{
location.SourceLocation{Line: 2, Column: 17},
},
},
gqlerrors.FormattedError{
Message: `Field "usernames" argument "usernames" of type "[String!]!" is required but not provided.`,
Locations: []location.SourceLocation{
location.SourceLocation{Line: 2, Column: 7},
},
},
},
}
result := graphql.Do(graphql.Params{
Schema: pluralTestSchema,
RequestString: query,
})
pretty.Println(result)
if !reflect.DeepEqual(result, expected) {
t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
}
}
示例8: ServeHTTPC
// ServeHTTPC handles requests as a xhandler.HandlerC
func (h *Handler) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) {
var query string
switch r.Method {
case "GET":
query = r.URL.Query().Get("query")
case "POST":
b, _ := ioutil.ReadAll(r.Body)
r.Body.Close()
if r.Header.Get("Content-Type") == "application/json" {
q := map[string]interface{}{}
if err := json.Unmarshal(b, &q); err != nil {
http.Error(w, fmt.Sprintf("Cannot unmarshal JSON: %v", err), http.StatusBadRequest)
}
query, _ = q["query"].(string)
} else {
query = string(b)
}
default:
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
result := graphql.Do(graphql.Params{
Context: ctx,
RequestString: query,
Schema: h.schema,
})
if resource.Logger != nil {
if len(result.Errors) > 0 {
resource.Logger(ctx, resource.LogLevelError, fmt.Sprintf("wrong result, unexpected errors: %v", result.Errors), nil)
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(result)
}
示例9: TestNodeInterfaceAndFields_AllowsRefetching_GetsTheCorrectWidthForPhotos
func TestNodeInterfaceAndFields_AllowsRefetching_GetsTheCorrectWidthForPhotos(t *testing.T) {
query := `{
node(id: "4") {
id
... on Photo {
width
}
}
}`
expected := &graphql.Result{
Data: map[string]interface{}{
"node": map[string]interface{}{
"id": "4",
"width": 400,
},
},
}
result := graphql.Do(graphql.Params{
Schema: nodeTestSchema,
RequestString: query,
})
if !reflect.DeepEqual(result, expected) {
t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
}
}
示例10: TestMutation_WithClientMutationId_BehavesCorrectly_SupportsPromiseMutations
// Async mutation using channels
func TestMutation_WithClientMutationId_BehavesCorrectly_SupportsPromiseMutations(t *testing.T) {
query := `
mutation M {
simplePromiseMutation(input: {clientMutationId: "abc"}) {
result
clientMutationId
}
}
`
expected := &graphql.Result{
Data: map[string]interface{}{
"simplePromiseMutation": map[string]interface{}{
"result": 1,
"clientMutationId": "abc",
},
},
}
result := graphql.Do(graphql.Params{
Schema: mutationTestSchema,
RequestString: query,
})
if !reflect.DeepEqual(result, expected) {
t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
}
}
示例11: ContextHandler
// ContextHandler provides an entrypoint into executing graphQL queries with a
// user-provided context.
func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
// get query
opts := NewRequestOptions(r)
// execute graphql query
params := graphql.Params{
Schema: *h.Schema,
RequestString: opts.Query,
VariableValues: opts.Variables,
OperationName: opts.OperationName,
Context: ctx,
}
result := graphql.Do(params)
if h.pretty {
w.WriteHeader(http.StatusOK)
buff, _ := json.MarshalIndent(result, "", "\t")
w.Write(buff)
} else {
w.WriteHeader(http.StatusOK)
buff, _ := json.Marshal(result)
w.Write(buff)
}
}
示例12: TestNodeInterfaceAndFields_AllowsRefetching_GetsTheCorrectNameForUsers
func TestNodeInterfaceAndFields_AllowsRefetching_GetsTheCorrectNameForUsers(t *testing.T) {
query := `{
node(id: "1") {
id
... on User {
name
}
}
}`
expected := &graphql.Result{
Data: map[string]interface{}{
"node": map[string]interface{}{
"id": "1",
"name": "John Doe",
},
},
}
result := graphql.Do(graphql.Params{
Schema: nodeTestSchema,
RequestString: query,
})
if !reflect.DeepEqual(result, expected) {
t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
}
}
示例13: customHandler
func customHandler(schema *graphql.Schema) func(http.ResponseWriter, *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
opts := handler.NewRequestOptions(r)
rootValue := map[string]interface{}{
"response": rw,
"request": r,
}
params := graphql.Params{
Schema: *schema,
RequestString: opts.Query,
VariableValues: opts.Variables,
OperationName: opts.OperationName,
RootObject: rootValue,
}
result := graphql.Do(params)
jsonStr, err := json.Marshal(result)
if err != nil {
panic(err)
}
rw.Header().Set("Content-Type", "application/json")
rw.Header().Set("Access-Control-Allow-Credentials", "true")
rw.Header().Set("Access-Control-Allow-Methods", "POST")
rw.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
rw.Header().Set("Access-Control-Allow-Origin", "http://localhost:8080")
rw.Write(jsonStr)
}
}
示例14: TestMutateAndGetPayload_AddsErrors
func TestMutateAndGetPayload_AddsErrors(t *testing.T) {
query := `
mutation M {
simpleMutation(input: {clientMutationId: "abc"}) {
result
clientMutationId
}
}
`
expected := &graphql.Result{
Data: map[string]interface{}{
"simpleMutation": interface{}(nil),
},
Errors: []gqlerrors.FormattedError{
gqlerrors.FormattedError{
Message: NotFoundError.Error(),
Locations: []location.SourceLocation{},
},
},
}
result := graphql.Do(graphql.Params{
Schema: mutationTestSchemaError,
RequestString: query,
})
if !reflect.DeepEqual(result, expected) {
t.Fatalf("wrong result, graphql result diff: %v", testutil.Diff(expected, result))
}
}
示例15: main
func main() {
// Save JSON of full schema introspection for Babel Relay Plugin to use
result := graphql.Do(graphql.Params{
Schema: data.Schema,
RequestString: testutil.IntrospectionQuery,
})
if result.HasErrors() {
log.Fatalf("ERROR introspecting schema: %v", result.Errors)
return
} else {
b, err := json.MarshalIndent(result, "", " ")
if err != nil {
log.Fatalf("ERROR: %v", err)
}
err = ioutil.WriteFile("../data/schema.json", b, os.ModePerm)
if err != nil {
log.Fatalf("ERROR: %v", err)
}
}
// TODO: Save user readable type system shorthand of schema
// pending implementation of printSchema
/*
fs.writeFileSync(
path.join(__dirname, '../data/schema.graphql'),
printSchema(Schema)
);
*/
}