Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to define a Map Object in GraphQL Schema?

I try to map a key string with arrays of Objects.

I can create a simple Object but i want to add easily an object in these arrays. The Map Object is perfect to do this.

Problem: I dont know how to define the Type Map for GraphQL :'(

@ObjectType()
export class Inventaire
  @Field()
  _id: string;

 @Field()
  stocks: Map<string, Article[]>;
}
like image 907
Tanguy Paqueto Dé Pépito Avatar asked Sep 02 '25 04:09

Tanguy Paqueto Dé Pépito


1 Answers

GraphQL does not provide any kind of map type out of the box. A JSON blob of key-value pairs do not have a strong schema, so you can't have something like this:

{
    key1: val1,
    key2: val2,
    key3: val3,
    ...
}

However, you can define a GraphQL Schema to have a key-value tuple type, and then define your property to return an array of those tuples.

type articleMapTuple {
     key: String
     value: Article
}

type Inventaire {
     stocks: [articleMapTuple]
}

Then your return types would look something like this:

    data [
    {
        key: foo1,
        value: { some Article Object}
    },
    {
        key: foo2,
        value: { some Article Object}
    },
    {
        key: foo3,
        value: { some Article Object}
    },
]

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!