2

I have been playing with the simple problem for days now and can not figure out my error. I am trying to return one object from an array of object with the object id.

playground query

schema definition

type Query {
info: String
feed: [Link!]
link(id: String!): Link
}

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

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

index.js

const { GraphQLServer } = require('graphql-yoga');

let links = [{
id: 'link-0',
url: 'www.howtographql.com',
description: 'Fullstack tutorial for GraphQL',
author: 'sam roehrich'
}]

let idCount = links.length

const resolvers = {
Query: {
info: () => `This is the API of a Hackernews Clone`,
feed: () => links,
link: (parent, {id}) => {
  return links.filter(link => {
    link.id === id
  })
}
}
Sam Roehrich
  • 123
  • 1
  • 6
  • 1
    According to its type, your field should return an object, but your resolver is returning an array of objects instead. See [Common Scenario #2](https://stackoverflow.com/a/56319138/6024220). – Daniel Rearden Feb 16 '20 at 19:02

2 Answers2

2

Way late to the party, but I thought I'd give a clear answer to this question for others in a similar situation.

Daniel Rearden in the comments is right. Basically, the problem is that the filter() function returns an array instead of an Object. A simple solution to this problem would be to return the first (and only) item of the array in the resolver:

const link = links.filter(link => {
    link.id === id
})
// Return only the first link from the array.
return link[0];
Nikitas IO
  • 696
  • 5
  • 20
0

filter returns a new list that satisfy the given condition, so you're returning a list than an item(object) of the list