Golang,gorm, postgress: invalid input is inserted

Golang,gorm, postgress: invalid input is inserted


0

when i perform request using

https://localhost:8080/graphql end point

I cant create user using mutation

    **the whole code:**

    package main

   import (
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/graphql-go/graphql"
    "github.com/graphql-go/handler"
    "github.com/kaleabbyh/foodrecipie/config"
    _ "github.com/lib/pq"
    )



    ** Note: the table users is succesfullly migrated using separate 
    migration code having 'User' attributes**

    type User struct {
    ID        int       `gorm:"type:int;primary_key;identity(100,1)"`
    Name      string    `gorm:"type:varchar(255);not null"`
    Email     string    `gorm:"uniqueIndex;not null"`
    Password  string    `gorm:"not null"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"updated_at"`
    }


    func checkErr(err error) {
    if err != nil {
        panic(err)
    }
    }

    func main() {
    
    config, err := Connection.LoadConfig(".")
    if err != nil {
        log.Fatal("? Could not load environment variables", err)
    }
    Connection.ConnectDB(&config)
    db:=Connection.DB

    userType := graphql.NewObject(graphql.ObjectConfig{
        Name:        "User",
        Description: "An user",
        Fields: graphql.Fields{

            "name": &graphql.Field{
                Type:        graphql.NewNonNull(graphql.String),
                Resolve: func(p graphql.ResolveParams) (interface{}, 
              error) {
                    if user, ok := p.Source.(*User); ok {
                        return user.Name, nil
                    }

                    return nil, nil
                },
            },
            "email": &graphql.Field{
                Type:        graphql.NewNonNull(graphql.String),
                Resolve: func(p graphql.ResolveParams) (interface{}, 
              error) {
                    if user, ok := p.Source.(*User); ok {
                        return user.Email, nil
                    }

                    return nil, nil
                },
            },
            "password": &graphql.Field{
                Type:        graphql.NewNonNull(graphql.String),
                Resolve: func(p graphql.ResolveParams) (interface{}, 
            error) {
                    if user, ok := p.Source.(*User); ok {
                        return user.Email, nil
                    }

                    return nil, nil
                },
            },
            
        },
    })

root mutation with full functionalities is here

rootMutation := graphql.NewObject(graphql.ObjectConfig{
            Name: "RootMutation",
            Fields: graphql.Fields{
                // user
                "createuser":&graphql.Field{
            

        Type:        userType,
                    Description: "Create new user",
                    Args: graphql.FieldConfigArgument{
                        "name": &graphql.ArgumentConfig{
                            Type: graphql.NewNonNull(graphql.String),
                        },
                        "email": &graphql.ArgumentConfig{
                            Type: graphql.NewNonNull(graphql.String),
                        },
                        "password": &graphql.ArgumentConfig{
                            Type: graphql.NewNonNull(graphql.String),
                        },
                    },
                    Resolve:func(params graphql.ResolveParams) 
               (interface{}, error) { input, ok := params.Args["input"]. 
                      (map[string]interface{})
                        fmt.Println(input)
                        if !ok {
                            return nil, fmt.Errorf("invalid input")
                        }
                    
                        name, _ := input["name"].(string)
                        email, _ := input["email"].(string)
                        password, _ := input["password"].(string)
                    
                        user := User{
                                Name:name,
                                Email :email,
                                Password:password,
                            }
                        err := db.Create(&user).Error
                        if err != nil {
                            return nil, err
                        }
                    
                        return user, nil
                    },
                },
            },
        })

root query with full functionalities is here

    rootQuery := graphql.NewObject(graphql.ObjectConfig{
        Name: "RootQuery",
        Fields: graphql.Fields{
            
            "users": &graphql.Field{
                Type:        graphql.NewList(userType),
                Description: "List of users.",
                Resolve: func(p graphql.ResolveParams) (interface{}, 
           error) {
                    
                    var users []User
                    err := db.Find(&users).Error
                    checkErr(err)
                    fmt.Println(users)
                    return users, nil
                
                },
            },
            
            
        },
    }) 

schema with full functionalities is here

    schema, _ := graphql.NewSchema(graphql.SchemaConfig{
        Query:    rootQuery,
        Mutation: rootMutation,
    })

    h := handler.New(&handler.Config{
        Schema:   &schema,
        Pretty:   true,
        GraphiQL: true,
    })

    // serve HTTP
    http.Handle("/graphql", h)
    fmt.Println("server is running on port: 8080")
    http.ListenAndServe(":8080", nil)
 }

resquest
this is the way I sent a resquest for mutation

    using https://localhost:8080/graphql

    mutation {
    createuser(
          name: "kaleab", 
          email: "[email protected]", 
          password: "random") {
        name
       } 
    }

**result **
this is the result I have got after I sent the request

    {
      "data": {
      "createuser": null
    },
    "errors": [
      {
      "message": "invalid input",
      "locations": [
          {
          "line": 2,
          "column": 3
         }
        ],
      "path": [
        "createuser"
        ]
       }
      ]
    }

New contributor

kaleab is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.


Load 3 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *