Graphql无法为不可为空的字段返回null

时间:2019-07-29 14:47:10

标签: graphql apollo-server

即使我的代码与书中的代码完全相同,我也一直在关注“ Learning GraphQL”这本书,但遇到了问题。

postPhoto和totalPhotos可以使用,但是无法查询allPhotos。 它说:“不能为非空字段Photo.id返回null。”并且,如果我删除了可为空的感叹号设置ID,则url字段也会出现同样的错误。

这是我的查询:

mutation newPhoto($name: String!, $description: String){
  postPhoto(name: $name, description: $description){
    id
    name
    description
  }
}

query listPhotos {
  allPhotos {
    id
    name
    description
    url
  }
}
const { ApolloServer } = require("apollo-server")

const typeDefs = `
    type Photo{
        id: ID!
        url: String!
        name: String!
        description: String
    }

    type Query {
        totalPhotos: Int!
        allPhotos: [Photo!]!
    }

    type Mutation {
        postPhoto(name: String! description: String): Photo!
    }
`

var _id = 0
var photos = []

const resolvers = {
  Query: {
    //return the length of the photos array
    totalPhotos: () => photos.length,
    allPhotos: () => photos
  },

  Mutation: {
    postPhoto(parent, args) {
      // parent is a reference to the parent object "Mutation" (=python self)
      var newPhoto = {
        id: _id++,
        ...args
      }
      console.log(newPhoto)
      photos.push(args)
      return newPhoto
    }
  }
}

//2. Create a new instance of the server.

//3. Send it an object with typeDefs (the schema) and resolvers
const server = new ApolloServer({
  typeDefs,
  resolvers
})

//4. Call listen on the server to launch the web server
server
  .listen()
  .then(({ url }) => console.log(`GraphQL Service runnng on ${url}`))

提前谢谢

0 个答案:

没有答案