N
N
NikitaZA2018-06-20 11:14:00
JavaScript
NikitaZA, 2018-06-20 11:14:00

How to display an array in a nested GraphQL query?

node server.
There is a user and his images, there are two arrays of objects. Images are attached to users.
Data from DB

obj =[{
  id: 1,
  name: "qwe",
    img: [
       {id: 1, name: "img1"},
       {id: 2, name: "img2"},
       {id: 3, name: "img3"},
    ]
}]

Upon request
{
  user(id:1){
    id name
    img{id name }
  }
}

I get
{
  "id": 1,
  "name": "qwe",
  "img": {
    "id": null
  }
}

If img is passed as an img object: {id: 1, name: "img1"}. That all works but one image is naturally transferred.
Gotta do it somehow
{
  "id": 1,
  "name": "qwe",
  "img":[ 
    {id: 1,  name: "img1"},
    {id: 2,  name: "img2"},
    {id: 3,  name: "img3"}
  ]
}

Tell me, poke your nose, but at least kick .... I can't figure out what the problem is.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NikitaZA, 2018-06-20
@NikitaZA

The problem is solved, and did not understand why it did not work. But this time all is well.
Scheme

const graphql = require('graphql');

const img = new graphql.GraphQLObjectType({
  name: "img",
  fields: () => {
    return {
      id: {type: graphql.GraphQLInt},
      idUser: {type: graphql.GraphQLInt}, 
      name: {type: graphql.GraphQLString}
    }
  }
})


const user = new graphql.GraphQLObjectType({
  name: 'user',
  description: 'This represents a Person',
  fields: () => {
    return {
      id: { 
        type: graphql.GraphQLInt,
        resolve (res) {
          return res.id;
        } 
      },
      mail: { 
        type: graphql.GraphQLString,
        resolve (res) {
          return res.mail;
        } 
      },
      password: { 
        type: graphql.GraphQLString,
        resolve (res) {
          return "privat info";
        } 
      },
      name: {
        type: graphql.GraphQLString,
        resolve (res) {
          return res.name;
        } 
      },
      img: {
        type: new graphql.GraphQLList(img),
      }
    };
  }
});
module.exports = user;

Request
const graphql = require('graphql');
const userSchema = require("../schema/userSchema")

module.exports = {
  type: new graphql.GraphQLList(userSchema),
  args: {
    id: {type: new graphql.GraphQLNonNull(graphql.GraphQLInt)}
  },
  resolve (source, args, context) {
    return [
      {
        id: 123,
        name: "pero",
        img: 
        [
          {id:  1, name: "pero111"},
          {id:  2, name: "pero112"},
          {id:  3, name: "pero113"}
        ]
        
      }
    ]
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question