graphql-spec icon indicating copy to clipboard operation
graphql-spec copied to clipboard

Map type

Open miracle2k opened this issue 11 years ago • 79 comments

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.

miracle2k avatar Oct 03 '15 08:10 miracle2k

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.

OlegIlyenko avatar Oct 03 '15 13:10 OlegIlyenko

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 https://github.com/graphql/graphql-js/issues/172 So :+1: to include specs for a "JSON or RawObject or however you want to call it" type.

Sandreu avatar Oct 17 '15 22:10 Sandreu

+1

xpepermint avatar Oct 18 '15 08:10 xpepermint

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: https://github.com/graphql/graphql-js/pull/172.

clintwood avatar Oct 20 '15 05:10 clintwood

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.

jvliwanag avatar Oct 23 '15 05:10 jvliwanag

@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 :crying_cat_face:

sonewman avatar Nov 09 '15 10:11 sonewman

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

D1plo1d avatar Nov 09 '15 15:11 D1plo1d

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

mincedmit avatar Dec 11 '15 20:12 mincedmit

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" }
  ]
}

leebyron avatar Jan 09 '16 00:01 leebyron

Please try to use JSON-LD language maps: http://www.w3.org/TR/json-ld/#index-maps

akuckartz avatar Jan 09 '16 14:01 akuckartz

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.

dylanahsmith avatar Mar 11 '16 07:03 dylanahsmith

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)

jackielii avatar Mar 21 '16 08:03 jackielii

+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..

Nebulai avatar May 23 '16 09:05 Nebulai

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

LucasIcarus avatar Jun 28 '16 14:06 LucasIcarus

+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).

juancabrera avatar Aug 05 '16 21:08 juancabrera

I have the same use case as @juancabrera. Our API delivers content defined and managed through a custom CMS, and a main feature is being flexible and dynamic. In the application, we model the objects as a base set of common fields, and then a "fields" map with all of the dynamic properties that we don't know about on the server.

{
  "contentId": 123456,
  "type": "video",
  "fields": {
    "title": "fake video 1",
    "releaseDate": "...",
    ...
  }
}

We'd like to give our client app devs the ability to query and transform the content in the way they want, but without having to create a strict schema on the server.

jarwol avatar Oct 13 '16 21:10 jarwol

+1 for maps. In my use-case I have objects of this shape (in typescript):

interface GenericObject { 
  id: string, 
  label: string,
  types: string[], 
  objectProps: {[key: string]: GenericObject[]}
  dataProps: {[key: string]}: string[]} 
}

Using the list of key-values would mean I am doing a transformation on the server to send the data and then do the reverse transformation on the client to build up that map again. Using the JSON value type would mean I can not fetch related objs (via objectProps) with their respective fields. Using arguments would mean I need to know all the properties in advance, which is not possible.

Also the size of data we talk about here is rather small. So paging is not an issue.

th-ko avatar Oct 21 '16 12:10 th-ko

We have the exact same need as @jarwol

rncry avatar Oct 28 '16 14:10 rncry

I am in agreement with @leebyron after watching what has happened in other "JSON" type apis at my company. The path of least resistance is the path most often traveled.

This means that if there is a choice of creating a new type that has more semantic meaning to the UI or creating a map that has no tooling support or contract, but is "quick" to create on the server, then a map is going to be used.

aweiker avatar Oct 28 '16 15:10 aweiker

I would personally opt for 2 seperated types. As I see it there are 2 use cases of the data:

  1. view, the data is shown to a user in his/her 's preferred language
  2. admin, the data is to be edited (translations added / changed / removed) by an administrative user

This might come across as perhaps anti-pattern, though in my opinion it is not. Since these are 2 completely separated concerns / representations even if the source for both is the same in your db.

Thus:

  1. VIEW: Type is the minimal set, language is given as a variable and resolver is responsible of choosing the correct one to return. Changes are high that you want localised data for more types then just "Item", therefore using a variable is also reusable across your schema queries, mutations, ...
type Item {
   title: String
 }

Selected by:

query ($language: String!) {
    Item(language:$language) {
        title
    }
    variables {
        language:'en-US'
    }
}
  1. ADMIN: Type is extensive administrative set. Here you can choose your own preferred medicine: Array based
type Language {
    code:String
    text:String
}
type Item {
    title: [Language]
}

Unified languages type (listing all possible?)

type Languages {
    nl-BE:String
    en-US:String
    fr-FR:String
    nl-FR:String
}

type Item {
    title:Languages
}

Plain object

scalar Object

type Item {
    title: Object
}

GroofyIT avatar Nov 08 '16 12:11 GroofyIT