33

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[]>;
}
1

3 Answers 3

40

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}
    },
]
6
  • 67
    "GraphQL is a strongly-typed language, and does not provide any kind of map type out of the box." like there are no strongly-typed languages that provide map type? There is no connection between the first and second half of the sentence.
    – Andrey
    Commented May 27, 2020 at 22:49
  • 7
    Maybe I should clarify - GraphQL is a strongly-typed language that does not provide any kind of map type out of the box. Therefore, you need to define your own.
    – user3126362
    Commented May 29, 2020 at 0:42
  • 6
    @gacharya the absence of Map type still doesn't have anything to do with strong typing. Maps are useful to represent data that is inherently a mapping. If used to represent properties of an object this is pretty bad and defeats the purpose of typing, but that's not the primary goal of maps.
    – Joffrey
    Commented Aug 25, 2020 at 7:42
  • 4
    a map construct is supported by every strongly typed language. Commented Mar 31, 2021 at 17:16
  • 7
    The key thing about a map is that every key is the same type and every value is the same type, so Map is also a strongly typed structure.
    – HubertNNN
    Commented Aug 26, 2021 at 13:42
4

You can use this package https://www.npmjs.com/package/graphql-type-json.

Example:

import { makeExecutableSchema } from 'graphql-tools';
import GraphQLJSON, { GraphQLJSONObject } from 'graphql-type-json';
 
const typeDefs = `
scalar JSON
scalar JSONObject
 
type MyType {
  myValue: JSON
  myObject: JSONObject
}
 
# ...
`;
 
const resolvers = {
  JSON: GraphQLJSON,
  JSONObject: GraphQLJSONObject,
};
 
export default makeExecutableSchema({ typeDefs, resolvers });
1
  • This package is included with permission in graphql-scalars which contains a bunch of other useful scalar types. Commented Jan 23, 2022 at 15:45
3

GraphQL does not natively support Map type. You can create your own scalar for Map or use existing ObjectScalar defined in repo https://github.com/graphql-java/graphql-java-extended-scalars

import graphql.Assert;
import graphql.language.ArrayValue;
import graphql.language.BooleanValue;
import graphql.language.EnumValue;
import graphql.language.FloatValue;
import graphql.language.IntValue;
import graphql.language.NullValue;
import graphql.language.ObjectValue;
import graphql.language.StringValue;
import graphql.language.Value;
import graphql.language.VariableReference;
import graphql.language.ObjectField;
import graphql.scalars.util.Kit;
import graphql.schema.Coercing;
import graphql.schema.CoercingParseLiteralException;
import graphql.schema.CoercingParseValueException;
import graphql.schema.CoercingSerializeException;
import graphql.schema.GraphQLScalarType;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ObjectScalar extends GraphQLScalarType {
    public ObjectScalar() {
        this("Object", "An object scalar");
    }

    ObjectScalar(String name, String description) {
        super(name, description, new Coercing<Object, Object>() {
            public Object serialize(Object input) throws CoercingSerializeException {
                return input;
            }

            public Object parseValue(Object input) throws CoercingParseValueException {
                return input;
            }

            public Object parseLiteral(Object input) throws CoercingParseLiteralException {
                return this.parseLiteral(input, Collections.emptyMap());
            }

            public Object parseLiteral(Object input, Map<String, Object> variables)
                    throws CoercingParseLiteralException {
                if (!(input instanceof Value)) {
                    throw new CoercingParseLiteralException("Expected AST type 'StringValue' but" +
                            " was '" + Kit.typeName(input) + "'.");
                } else if (input instanceof NullValue) {
                    return null;
                } else if (input instanceof FloatValue) {
                    return ((FloatValue)input).getValue();
                } else if (input instanceof StringValue) {
                    return ((StringValue)input).getValue();
                } else if (input instanceof IntValue) {
                    return ((IntValue)input).getValue();
                } else if (input instanceof BooleanValue) {
                    return ((BooleanValue)input).isValue();
                } else if (input instanceof EnumValue) {
                    return ((EnumValue)input).getName();
                } else if (input instanceof VariableReference) {
                    String varName = ((VariableReference)input).getName();
                    return variables.get(varName);
                } else {
                    List values;
                    if (input instanceof ArrayValue) {
                        values = ((ArrayValue)input).getValues();
                        return values.stream().map((v) -> {
                            return this.parseLiteral(v, variables);
                        }).collect(Collectors.toList());
                    } else if (input instanceof ObjectValue) {
                        values = ((ObjectValue)input).getObjectFields();
                        Map<String, Object> parsedValues = new LinkedHashMap();
                        values.forEach((fld) -> {
                            Object parsedValue = this.parseLiteral(((ObjectField)fld).getValue(),
                                    variables);
                            parsedValues.put(((ObjectField)fld).getName(), parsedValue);
                        });
                        return parsedValues;
                    } else {
                        return Assert.assertShouldNeverHappen("We have covered all Value types",
                                new Object[0]);
                    }
                }
            }
        });
    }
}

scalar Object

type Result {
 value : Object
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.