How to write graphql query wiith custom objects

2019-08-03 03:36发布

问题:

The server side of graphql is with nodejs and express. This is the schema for graphql. It has one query which accepts DateT object having from and to dates.

var schema = buildSchema(`
    type Query {
        courseWithDate(
            timeFilter: DateT
        ): Course

    },
    type Course {
        ...
        from: String
        to: String
    },
    type DateT{
        from : String
        to : String
    }
`);

and this is how I am getting courses

I am able to run the application with this url

localhost:4000/graphql

This is the query I am using

query courseWithDate($from: dateFrom, $to: dateTo) {
    courseWithDate(timeFilter: {
      from: "${dateFrom}"
      to: "${dateTo}"
    })  {
        title
        ...
    }
}

with these parameters

{ 
   "from": "2019-10-10","to":"2019-10-10"
}

Exception message I get is related to the input type I am trying to pass.

{
  "errors": [
    {
      "message": "The type of Query.courseWithDate(timeFilter:) must be Input Type but got: DateT.",
      "locations": [
        {
          "line": 6,
          "column": 25
        }
      ]
    }
  ]
}

回答1:

I'm not sure, but probably this style looks more like best practice

type Course {
  id: Int
  title: String
  author: String
  from: String
  to: String
  description: String
  topic: String
  url: String
}

input DateInput {
  dateFrom: String!
  dateTo: String!
}

type Query {
  courseWithDate(input: DateInput!, name: String!): Course
}

And Query on client side should be:

  {
    courseWithDate(input: {
      dateFrom: "${dateFrom}"
      dateTo: "${dateTo}"
    }
    name: "${name}") 
    {
      id
      name
    }
  }