Type-graphql: Is annotation Field( type => Map) supported?

Created on 4 Jul 2019  路  5Comments  路  Source: MichalLytek/type-graphql

Hi everyone,
I'm trying to implement i18n feature on my backend and I need to store different translations for fields that require to be localized (ex: name, description,...).
In my mind I though to design a field able to store a Map in order to provide the front-end a json like this:

{
    name: { en: "Book", de:"Buch", it="Libro"}
}   

In this way, the front-end will be able to get desired translation immediately simply calling:

var bookName = name[userLanguage]; //where user language is a context variable

I tryed to use the annotation @Field(type => Map) but I get the following error:

UnhandledPromiseRejectionWarning: Error: Cannot determine GraphQL output type for name
    at Function.getGraphQLOutputType (R:\Progetti\BiteCode\kaleidos-backend\node_modules\type-graphql\dist\schema\schema-generator.js:394:19)
    at objectType.fields.reduce (R:\Progetti\BiteCode\kaleidos-backend\node_modules\type-graphql\dist\schema\schema-generator.js:174:44)
    at Array.reduce (<anonymous>)

Since it seems that the usage of type "Map" is not supported, what is the best way to achieve this result?

Thanks in advance
Roberto

Question Solved

All 5 comments

You have to explicitly type all possible property names:

@ObjectType()
class Translations {
  @Field()
  en: string;

  @Field()
  de: string;

  @Field()
  it: string;
}

And then use such construct in your base type:

@ObjectType()
class Book{
  @Field(type => Translations)
  name: Translations;
}

Or if you don't need all translation on client at once, you can just ask for a translated string:

enum Language {
  EN
  DE
  IT
}

query {
  books {
    id
    pagesCount
    name(language: EN)
  }
}

In that case you need to do the name[userLanguage] mapping from db entity column to returned string in a field resolver.

Thanks a lot. This solution can work for me.

Closing for a housekeeping purposes 馃敀

It would be extremely tedious to type out all the possibilities. I would love to have this feature 馃憤

Does there exist a temporary solution for this to work?

It would be extremely tedious to type out all the possibilities

Welcome in the GraphQL world where everything has to be explicitly listed 馃憢

If you don't care about a type-safety and ability to select specific fields, you can retrieve the whole structure at once by two ways:

  • using GraphQLJSON scalar type
  • defining a key-value type and return an array of key-value object (e.g. using Object.entiries)
Was this page helpful?
0 / 5 - 0 ratings

Related issues

robertchung97 picture robertchung97  路  3Comments

itsgracian picture itsgracian  路  3Comments

Janushan picture Janushan  路  3Comments

tongtwist picture tongtwist  路  3Comments

Asim13se picture Asim13se  路  3Comments