1

so im working on a project of mine and i seem to hit a dead end with my abilities.

I am working on a GraphQL backend that is supposed to fetch some data from a MySQL database. I already got the resolvers working so i can fetch all users etc. but i am not able to fetch nested types. For example:

query {
  ways {
    id
    distance
    duration
    purpose
    User {
      id
      dob
    }
  }
}

This only returns all the ways from my database but the User returns null

schema.ts

export const typeDefs= gql`
    schema {
        query: Query
    }

    type Query {
        ways: [Way]
        users: [User]
        getUser(id: String!): User
        getWay(id: String!):Way
    }
    type Way{
        id:String
        distance:Float
        duration:Float
        stages:[Stage]
        purpose:String
        User:User
    }
    type User{
        id:String
        firstname:String
        lastname:String
        sex:String
        dob:String
        annualTicket:Boolean
        Ways:[Way]
    }

resolver.ts

export const resolvers = {
  Query: {
    ways: async(parent, args, context, info) => {
      console.log("ways")
      const answer=await getAllWays();
      return answer;
    },
    users: async(parent, args, context, info) => {
      console.log("users")
      const answer=await getAllUser();
      return answer;

    },
    getUser: async(parent, args, context, info) =>{
      console.log("getUser")
      const answer=await getUserPerID(args.id);
      return answer;
    },
    getWay:async(parent, args, context, info) =>{
      console.log("getWay")
      const answer=await getWayPerID(args.id);
      return answer;
    }
  },
  User:async(parent, args, context, info) =>{
    console.log("User: id="+args.id)
    ways: User => getWaysPerUserID(args.id)
  },
  Way:async(parent, args, context, info) => {
    console.log("Way: id="+parent.userID)
    user: Ways => getUserPerID(parent.userID)
  }

I would expect the outcome to include the user and its data too, using the above mentioned query.

Any advice is much appreciated.

DDaniel
  • 25
  • 3

1 Answers1

0

Only fields, not types, can have resolvers. Each key in your resolvers object should map to another object, not a function. So instead of

Way:async(parent, args, context, info) => {
  console.log("Way: id="+parent.userID)
  user: Ways => getUserPerID(parent.userID)
}

You need to write:

Way: {
  // We capitalize the field name User because that's what it is in your schema
  User: (parent) => getUserPerID(parent.userID)
}
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • can you please help me [here](https://stackoverflow.com/questions/55729574/write-dynamic-schema-for-return-same-result-in-graphql) – Ashok Apr 17 '19 at 14:21