Search code examples
javascriptsyntaxschemagraphqlresolver

Cannot delete a post with Graphql


I am having an issue with getting my resolver function to work properly.

Here is my resolver function:

const resolvers = {
  Query: {
    info: () => `This is the API of a Hackernews Clone`,
    // 2
    feed: () => links,
  },
  // 3
  Mutation: {
    // 2
    post: (parent, args) => {
       const link = {
        id: `link-${idCount++}`,
        description: args.description,
        url: args.url,
      }
      links.push(link)
      return link
    },
       deleteLink: (parent, args) => {
        const  id = args.id
        //delete links[id1]
        return  id
    }
  }
}

Here is my schema:

type Query {
  info: String!
  feed: [Link!]!
}

type Mutation {
  post(url: String!, description: String!): Link!
  deleteLink(id: ID!): Link

}

type Link {
  id: ID!
  description: String!
  url: String!
}

When I use this block to run my deleteLink resolver:

mutation {
  deleteLink(
    id: "link-1"
  ){
    id
  }
}

I get an error like this one:

{
  "data": {
    "deleteLink": null
  },
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Link.id.",
      "locations": [
        {
          "line": 3,
          "column": 5
        }
      ],
      "path": [
        "deleteLink",
        "id"
      ]
    }
  ]
}

Please let me know what I am doing wrong. I am not sure why i get the error: cannot return null for non-nullable field Link.id. Is this a result of the wrong way to query the mutation or is this a result of a bad resolver function?


Solution

  • According to your schema, your deleteLink mutation returns a Link object type and a Link returns id, description, url as required fields.

    In your resolver, you are only returning a id and null for all the rest.

    The best approach in my opinion would be to change your mutation return type into a String or ID type. When you delete a record, you can't (should not) return the same record, but should return a status/id message.

    Something like:

    type Mutation {
      post(url: String!, description: String!): Link!
      deleteLink(id: ID!): String! // Or ID! if you want to return the input id
    }