Skip to content

Map type #101

Open
Open

Description

@miracle2k

Should there be a map type?

I have a structure that looks like this:

  Item {
     title {
        de_DE,
        fr,
        pa,
        .....
     }
  }

The point here is that the number of language strings might be arbitrary. I find this hard to model using GraphQLObject, because:

  1. The number of locales is undefined. While the resolver could handle this dynamically, I think it's a problem in Relay that the schema cannot reflect these dynamic fields.
  2. I would like to query all the existing locales, which isn't allowed, it seems ("must have a sub-selection").

If I make my GraphQL server return a JSON object for "title", the Relay client doesn't complain (although maybe shouldComponentUpdate breaks), but I think I'm skirting by here. At the very least, I think I couldn't generate a schema that confirms to the spec.

Activity

  1. OlegIlyenko commented on Oct 3, 2015

    @OlegIlyenko
    Contributor

    I think this is a valid concern as well. I currently thinking of ways to add GraphQL endpoint for our API. We are building project-based multi-tenant service. For example every project has a list of products which have name and description. Just like in your case these are localized strings as well.

    One way one can approach this problem is to parametrize the field:

    query ProductNames {
      products {
        nameEn: name(locale: "en")
        nameDe: name(locale: "de_DE")
      }
    }

    Another approach, as you mentioned, would be to generate a schema of-the-fly. In our case it would be possible, since every project has a limited set of locales which are defined in the config of this project.

    Where it becomes more tricky is an addition user-defined data types. Users of our API can define new attributes for products (visually through the merchant-center application). These attributes are also typed, so it's possible to generate GraphQL schema for this project, but it has some implications:

    • Generating schema on every request comes with big performance penalty, since we need to load config from a DB in order to do so
    • to compensate for this performance penalty we need to implement some schema caching and cache invalidation logic
    • Schema now becomes tenant-specific. This means that it becomes much harder to integrate with generic tools like GraphiQL and do introspection in general
    • You can't even do an introspection queries without the auth anymore.

    I guess one can just put all custom attribute JSON in a string scalar, but I don't think that other developers will appreciate JSON inside of string inside of another JSON :) I feel that generic JSON/Map-like type can provide a very useful middle-ground for these use-cases. It can also help a lot with a migration to the GraphQL. One can quickly start with Map-like structure and after some time develop schema generation and caching mechanisms.

  2. Sandreu commented on Oct 17, 2015

    @Sandreu

    Hello,

    I agree about this, and as @OlegIlyenko said, JSON string inside JSON string seems awkward.
    I think Map is one portion of what JSON can provide and I have exposed my point of view in graphql/graphql-js#172
    So 👍 to include specs for a "JSON or RawObject or however you want to call it" type.

  3. xpepermint commented on Oct 18, 2015

    @xpepermint
    Contributor

    +1

  4. clintwood commented on Oct 20, 2015

    @clintwood

    Hi,

    I have a use case where I have 'server based schema' and 'client based schema'. The server based schema is pretty much static and will follow normal project/application changes through time. However the client based schema is specific to client side and generated on the fly for exclusive use by the client/user. It's shape is not ideal for a generic map type as it can become deeply hierarchical.

    What I need to do is store the resulting client side JSON blob against the user on the server side. I specifically do not want any validation or type checking done on this JSON blob server side except for checking for valid JSON. At the moment I'm storing it as stringified JSON against an attribute in server side schema which does not seem ideal.

    So I'm very much in favor of JSONObject/RawObject/UncheckedObject or whatever as simple JSON object as proposed here: graphql/graphql-js#172.

  5. jvliwanag commented on Oct 23, 2015

    @jvliwanag

    It looks like the use case of @miracle2k can be solved by just using a list. So something like:

      Item {
         titles {
            language
            text
         }
      }
    

    wherein titles is an array. One can always create an input argument if you want to select a subset.

    @clintwood 's use case however looks different since there's no known schema and may be hierarchical.

    IMO, as long as there's a known structure, a list type could replace a map.

  6. sonewman commented on Nov 9, 2015

    @sonewman

    @jvliwanag correct me if I am wrong, but this would mean that the values in the list would have to return as an array. This is OK if someone is developing an API from scratch and has control over defining the response payload.

    But if an existing API is being moved over to use GraphQL, which already has a defined contract returning a map of key value pairs (even if the values are always of a defined object type / structure), then it appears this is unavoidable.

    I am interested to know how it would be possible to use a list, unfortunately the the list type does not seem to accept anything except an array:
    graphql/graphql-js/blob/master/src/execution/execute.js#L679-L683.

    Interestingly the error:

     User Error: expected iterable, but did not find one.
    

    Suggests it could be possible to supply a Map or Set, but of course the code says otherwise 😿

  7. D1plo1d commented on Nov 9, 2015

    @D1plo1d

    +1. Maps would be useful in mutations for sending arbitrary key/value pairs.

  8. mincedmit commented on Dec 11, 2015

    @mincedmit

    +1 as well, imagine this can also allow for embedded documents in query responses if using a record store on the backend?

  9. leebyron commented on Jan 9, 2016

    @leebyron
    Collaborator

    Support in the JS library itself for arbitrary iterables rather than just Arrays is coming soon.

    There are significant tradeoffs to a Map type vs a list of key/value pairs. One issue is paginating over the collection. Lists of values can have clear pagination rules while Maps which often have non-ordered key-value pairs are much more difficult to paginate.

    Another issue is usage. Most often Map is used within APIs where one field of the value is being indexed, which is in my opinion is an API anti-pattern as indexing is an issue of storage and an issue of client caching but not an issue of transport. This anti-pattern concerns me. While there are some good uses for Maps in APIs, I fear that the common usage will be for these anti-patterns so I'm suggesting proceeding with caution.

    For the original post, I think there are two good ways to solve this API puzzle:

    First is what @OlegIlyenko suggests. That you explicitly ask for the languages which you care about fetching. If you need multiple you can use aliases to query for multiple. This may be the right path if you know up front which you want to query.

    item {
      title: title(lang: $custom_lang)
      title_en: title(lang: "en")
      title_fr: title(lang: "fr")
    }
    

    Second is returning a list of tuples. This may be the right path if you don't know up front which you want, or if you specifically want them all.

    item {
      titles {
        language
        text
      }
    }
    

    such that you might get the result:

    "item": {
      "titles": [
        { "language": "en", text: "Hello" },
        { "language": "fr", text: "Bonjour" }
      ]
    }
    
  10. dylanahsmith commented on Mar 11, 2016

    @dylanahsmith
    Contributor

    I agree with @leebyron about the solution to the original problem.

    In the case of user-defined JSON data, can we just make it clear that custom scalars aren't restricted to how they can be serialized. E.g. with graphql-js you can serialize a custom JSON scalar using arrays, objects, etc.

  11. jackielii commented on Mar 21, 2016

    @jackielii

    alternatively:

    item {
      titles(languages: ["en", "fr"])
    }
    

    result:

    "item": {
      "titles": ["Hello", "Bonjour"]
    }
    

    You can specify the list of language in a variable

    Advantage of this approach:

    1. static query: no need to specify languages before writing the fragment (versus approach 1 in @leebyron 's comment
    2. didn't create a new Object type. (versus approach 2 in @leebyron 's comment)
  12. Nebulai commented on May 23, 2016

    @Nebulai

    +1 for map support. This "anti-pattern" logic seems like over-thinking it to me. Sure some people will abuse it but that is true for anything..

  13. LucasIcarus commented on Jun 28, 2016

    @LucasIcarus

    +1, map support is useful for some situations that the system always return less data than expect, I think.

  14. juancabrera commented on Aug 5, 2016

    @juancabrera

    +1 Currently I'm dealing with an API that data is arbitrary (as users can create their own contentTypes on the CMS), so there is no way I can create an entryType as I have no idea what fields are in there. Having a mapType will be super useful for these cases.

    Update: Just tried this and is working great so far!: https://github.com/taion/graphql-type-json (thank you @taion).

  15. 54 remaining items

  16. m4nuC commented on Oct 13, 2018

    @m4nuC

    Hypothetical use case where a Map type could come in handy:

    Imagine dealing with a Humans type that has a Genome property which holds a bunch of genes. Each gene has a name and value. The entire possibilities for that Genome are known but can greatly vary from one Human to the other. So it would result in a very tedious and rather hard to maintain union type. There is no interest in running queries for particular genes, but we might want to retrieve the entire genome when getting a Human.

    What would be the idiomatic GraphQL way to go about this?

  17. taion commented on Oct 15, 2018

    @taion

    You'd do something like:

    type Human {
      genome: [Gene]
    }
    
    type Gene {
      name: String
      value: String
    }

    i.e. otherwise follow the "list of entries" pattern as above.

  18. jlouis commented on Oct 15, 2018

    @jlouis

    To add to @taion's writings:

    In Protocol Buffers version 3, there is a handy support for a Map type. This type has an internal representation which follows the above. That is Map<K, V> is represented as [MapEntry] where type MapEntry { key: K, value: V }. This means:

    • It is backwards compatible. Older clients use that format.
    • It is not excessively larger on the wire.

    It somewhat suggests that Map types is an artifact of the Client more than it is an artifact of the GraphQL "wire"-representation. Like the Relay NG specification adds special handling of objects with a "Connection" suffix, one could determine a special set of rules for a "Map" suffix, based on the above scheme.

  19. iNahooNya commented on Oct 25, 2018

    @iNahooNya

    +1 for map support.
    One side I wants to enlarge our graphQL service cover, in other side our client wants a more effective structure like map. They got map, they will transfer it to old modules easily.

  20. longzero1888 commented on Nov 15, 2018

    @longzero1888

    +1 my team really really really need this!!!

  21. villesau commented on Mar 20, 2019

    @villesau

    If someone is worried about abusing Map type, wouldn't it make much more sense to write a linter for GraphQL which allows you to limit the functionality instead of restricting it by design?

  22. EgidioCaprino commented on Mar 25, 2019

    @EgidioCaprino

    It would be great if you could use Flow style like:

    type Foo {
      [String!]: Boolean
    }
    
  23. alkismavridis commented on Apr 13, 2019

    @alkismavridis

    I think the most straight-forward syntax to define the map would be something like that:

    type Bar {
      myField: Foo
      myList: [Foo]
      myMap: [String : Foo]
    }
    
  24. mfaisalhyder commented on Apr 16, 2019

    @mfaisalhyder

    type User {
    name: String
    address: String
    property: map[ key: String/[String] value: String/[complexType] ]
    }
    If we declare it this way it will be good as well.

  25. keynan commented on Jul 10, 2019

    @keynan

    +1

    // schema {
    property: map[ key: String, value: ComplexType ]
    }
    
    // query {
      property: map[
        key,
        value: {
          id
        }
      ]
    }
    
  26. elkowar commented on Aug 21, 2019

    @elkowar

    I'd also realllllly need this, as im building an api server that serves key-value pairs the client can't know the keys for... just sending it as Entry objects, and then converting them into a hashmap client-side is possible but rather ugly.

  27. adzimzf commented on Sep 12, 2019

    @adzimzf

    We really need this

  28. locked as resolved and limited conversation to collaborators on Sep 16, 2019
  29. leebyron commented on Sep 16, 2019

    @leebyron
    Collaborator

    I'm going to lock this issue since it has become non-actionable.

    For anyone arriving here looking for a Map type, I suggest first reading the comments on this thread about the API design tradeoffs and alternative approaches available. If someone feels strongly that this concept deserves first-class support in GraphQL, then I suggest following the RFC procedure to take this from a general suggestion to an actual proposal. Find more information about that process here https://github.com/facebook/graphql/blob/master/CONTRIBUTING.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    👻 Needs Champion💭 Strawman (RFC 0)

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions