Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mutation Output Fields #46

Closed
pyrossh opened this issue Nov 3, 2015 · 3 comments
Closed

Mutation Output Fields #46

pyrossh opened this issue Nov 3, 2015 · 3 comments
Labels

Comments

@pyrossh
Copy link
Contributor

pyrossh commented Nov 3, 2015

I have a custom scalar type and a mutation like this

   var PLID = types.NewGraphQLScalarType(types.GraphQLScalarTypeConfig{
        Name: "PLID",
        Serialize: func(value interface{}) interface{} {
            return value
        },
        ParseValue: func(value interface{}) interface{} {
            var err error
            switch value.(type) {
            case string:
                err = validate(value.(string))
            default:
                err = errors.New("Must be of type string")
            }
            if err != nil {
                // panic(err) // TODO: This panic kills the server
            }
            return value
        },
        ParseLiteral: func(valueAst ast.Value) interface{} {
            if valueAst.GetKind() == kinds.StringValue {
                err := validate(valueAst.GetValue().(string))
                if err != nil {
                    panic(err)
                }
                return valueAst
            } else {
                panic("Must be of type string")
            }
        },
    })

var RootMutation = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
    Name: "Mutation",
    Fields: types.GraphQLFieldConfigMap{
       "UserLogin": gqlrelay.MutationWithClientMutationId(gqlrelay.MutationConfig{
            Name: "UserLogin",
            InputFields: types.InputObjectConfigFieldMap{
                "email": &types.InputObjectFieldConfig{
                    Type: types.NewGraphQLNonNull(PLEmail),
                },
                "password": &types.InputObjectFieldConfig{
                    Type: types.NewGraphQLNonNull(PLPassword),
                },
            },
            OutputFields: types.GraphQLFieldConfigMap{
                "user": &types.GraphQLFieldConfig{
                    Type: PLID,
                },
            },
            MutateAndGetPayload: func(inputMap map[string]interface{}, info types.GraphQLResolveInfo) map[string]interface{} {
                user := &User{ID: "tester", "email": "test@mail.com", "password": "tester"}
                return map[string]interface{}{"user": user}
            },
        }),
    },
})

and when I do a mutation like this,

mutation Crud($input: UserLoginInput!) {
  UserLogin(input: $input) {
    user {
        id
        name
        email
    }
  }
}

// with variables
{
  "input": {
    "email": "abc2@mailinator.com",
    "password": "tester",
    "clientMutationId": "1"
  }
}

I get the whole object in the response even the password no matter what i specify in the query.

{
  "data": {
    "UserLogin": {
      "user": {
        "id": "9a84af9b-821a-11e5-8c98-201a06e4e14a",
        "password": "$s0$919553$V9kHnJF7rzPDwpHGKeLaCn0YG2Rw71wblMMys8wI/W4$VnZBf7/7HXm1SHGQNYmA6iVtPdjSo+JFAmf0EKOwU7w"
      }
    }
  }
}

Can a scalar type PLID here be reflected as an object and all its properties be rendered regardless of what was specified?
I tried the same query with PLID as graphqlString and I get the output like this,

{
  "data": {
    "UserLogin": {
      "user": "{id: '..', password: '..', dob: '..'}
    }
  }
}

basicially it stringifies the struct.

@sogko sogko added the question label Nov 6, 2015
@sogko
Copy link
Member

sogko commented Nov 6, 2015

Hi @pyros2097

I just got around to take a look into this now that we've gotten the major API change out of the way 😃

Hmm, to start with, I think there is a mismatch between what you have defined as the OutputField and the actual value that you return in MutateAndGetPayload.

Also, the above uses the relay library, which I think confuses most people who are not familiar with Relay (which is not part of GraphQL spec, but rather a separate "extension" that adds other stuff to it (i.e. global ID, pagination helpers etc)

I've re-written your example with pure GraphQL and using the new API.

package main

import (
    "errors"
    "github.com/graphql-go/graphql"
    "github.com/graphql-go/graphql/language/ast"
    "github.com/graphql-go/graphql/language/kinds"
    "github.com/kr/pretty"
)

func validate(value string) error {
    return nil
}

var PLID = graphql.NewScalar(graphql.ScalarConfig{
    Name: "PLID",
    Serialize: func(value interface{}) interface{} {
        return value
    },
    ParseValue: func(value interface{}) interface{} {
        var err error
        switch value.(type) {
        case string:
            err = validate(value.(string))
        default:
            err = errors.New("Must be of type string")
        }
        if err != nil {
            // panic(err) // TODO: This panic kills the server
        }
        return value
    },
    ParseLiteral: func(valueAst ast.Value) interface{} {
        if valueAst.GetKind() == kinds.StringValue {
            err := validate(valueAst.GetValue().(string))
            if err != nil {
                panic(err)
            }
            return valueAst
        } else {
            panic("Must be of type string")
        }
    },
})

type User struct {
    ID       string `json:"id"`
    Email    string `json:"email"`
    Password string `json:"password"`
}

var RootMutation = graphql.NewObject(graphql.ObjectConfig{
    Name: "Mutation",
    Fields: graphql.FieldConfigMap{
        "UserLogin": &graphql.FieldConfig{
            Name: "UserLogin",
            Type: PLID, // output is defined as our custom PLID scalar type.
            Args: graphql.FieldConfigArgument{
                "email": &graphql.ArgumentConfig{
                    Type: graphql.NewNonNull(graphql.String),
                },
                "password": &graphql.ArgumentConfig{
                    Type: graphql.NewNonNull(graphql.String),
                },
            },
            Resolve: func(p graphql.GQLFRParams) interface{} {
                // let's just print to verify that we have passed the variables correctly
                // expected output:
                // Arguments map[string]interface {}{
                //      "email": "john@doe.com",
                //      "password": "donkeykong",
                // }
                pretty.Println("Arguments", p.Args)

                // marshall and cast the arguments
                email, _ := p.Args["email"].(string)
                password, _ := p.Args["password"].(string)

                // perform mutation operation here
                // ...
                user := &User{
                    ID:       "id007" + email + password,
                    Email:    email,
                    Password: password,
                }

                // I'm assuming this is the desired output (i.e. user.ID: PLID)
                return user.ID
            },
        },
    },
})
var RootQuery = graphql.NewObject(graphql.ObjectConfig{
    Name: "Query",
    Fields: graphql.FieldConfigMap{
        "currentID": &graphql.FieldConfig{
            Type: graphql.String,
        },
    },
})

func main() {

    // define our schema.
    // note that while mutation is optional, root query is not. So we defined a trivial root query here.
    mutationsTestSchema, err := graphql.NewSchema(graphql.SchemaConfig{
        Query:    RootQuery,
        Mutation: RootMutation,
    })
    if err != nil {
        panic(err)
    }

    // the variables that would be passed into `graphql`
    // I've intentionally used `emailVar` and `passwordVar`
    // to make the mutation query easier to understand
    variables := map[string]interface{}{
        "emailVar":    "john@doe.com",
        "passwordVar": "donkeykong",
    }

    // our mutation query
    request := `
        mutation Crud($emailVar: String!, $passwordVar: String!) {
          UserLogin(email: $emailVar, password: $passwordVar) {
            user {
                id
                name
                email
            }
          }
        }
    `
    p := graphql.Params{
        Schema:         mutationsTestSchema,
        VariableValues: variables,
        RequestString:  request,
    }
    result := graphql.Graphql(p)
    pretty.Println(result)
    // Expected output:
    //  &graphql.Result{
    //      Data: map[string]interface {}{
    //          "UserLogin": "id007john@doe.comdonkeykong",
    //      },
    //      Errors: nil,
    //  }
}

Output

Arguments map[string]interface {}{
    "email":    "john@doe.com",
    "password": "donkeykong",
}
&graphql.Result{
    Data: map[string]interface {}{
        "UserLogin": "id007john@doe.comdonkeykong",
    },
    Errors: nil,
}

Notes:

  • No changes to your original PLID Scalar definition, besides updating the API.
  • Notice that the schema definition for mutation using pure GraphQL is much simpler than Relay.
    • Define your inputs using Args.
    • Define your output type using Type
    • Define your mutation operation in the Resolve function, and return the value that matches the output type defined previously in Type
  • I've intentionally used emailVar and passwordVar for the keys in the input variables to highlight the differences in the mutation query.
  • Note the PLID has to be a scalar value (i,e string, boolean, int, etc). Your original example returned a struct instead, probably thats why the output got stringified.

Hope this help a little! Cheers!

@pyrossh
Copy link
Contributor Author

pyrossh commented Nov 7, 2015

Hi @sogko,

Thanks for looking into this and the pure graphql example. My thoughts here was when I return the user struct for a scalar type like graphql.String Type,

user := &User{
    ID:       "id007",
    Email:    email,
    Password: password,
}
Arguments map[string]interface {}{
    "email":    "john@doe.com",
    "password": "donkeykong",
}
&graphql.Result{
    Data: map[string]interface {}{
        "UserLogin": "&{id007 john@doe.com donkeykong}",
    },
    Errors: nil,
}

it serializes it as a string so my web response will be like this

{
  "data": {
    "UserLogin": "&{id007 john@doe.com donkeykong}",
  }
}

but If I use a scalar type PLID then my response Is like this,

{
  "data": {
    "UserLogin": {
        "id": "007",
        "password": "bash"
      }
  }
}

(I haven't tried this yet in the new version and using graphiql will do it soon)
I thought Scalar's can only return one value and not objects, Based on the response it looks like my UserLogin Ouput is an ObjectType with fields id and password which is not true. This became an issue when I noticed the password also present as I forgot to remove it from the struct which could become dangerous, as we could expose other important data accidentally using scalars.

But Now I notice the serialize part of the PLID scalar and I think I should be doing the type conversion there and returning only the ID.

So I was wondering should'nt graphql throw an error if we return an object for a Scalar Type, I still have to re-implement this in graphql-js and see if it happens there also.

@Fontinalis
Copy link
Collaborator

Closing issue since there was no comment in more than 3 years.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants