0
votes

Let's imagine we have GraphQL API that can return an object Entity with Id and Name properties and I requested Name only:

query {
    entities {
        name
    }
}

And it returns

{
    "data": {
        "entities": [
        {
            "name": "Name1"
        },
        {
            "name": "Name2"
        }
        ]
    }
}

But what if I want to have only the name of entities as a scalar type? In other words, I want to have something like:

{
    "data": {
        "entities": [
            "Name1",
            "Name2"
        ]
    }
}

Is it possible to have such result without changes on the GraphQL API side? Aliases, Fragments, etc. GraphQL has a lot of built-in query capabilities, but none of the known me can return complex objects as scalar type.

1
Share the Type definition schema for Entities? - fortunee
entities(): [Entity] Entity: id: int! name: String - DevForRest
You can create an enum type with values Name1, Name2.. but you will need server side changes to let graphql know how to process the enum - Mat G
Thanks, but I have few clients with different needs, trying to find way without changes, GraphQL is flex for that, but not in all cases :-( - DevForRest

1 Answers

0
votes

what you're asking for is almost impossible if you don't want to change the type definition for Entities.

This: 👇🏽

Entity: id: int! name: String
entities(): [Entity]

returns an array of objects with keys name and id.

To achieve what you're asking you either change Entity to be just a string or have your client reduce that object to an array of just Entity names when they receive it.

They could do something like this:

const data = {
  entities: [
    {
      name: 'Name1',
    },
    {
      name: 'Name2',
    },
  ],
};

const entityNames = data.entities.reduce(
  (acc, curr) => [...acc, curr.name],
  []
);

console.log(entityNames);