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
{
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
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:
Object.entiries)