Answer the question
In order to leave comments, you need to log in
How to translate GraphQL error messages for Rails 6 using internationalization?
How can I translate a GraphQl error message using rails internationalization?
Using just the backend?
For example, I have a GraphiQL output, with a message field :
{
"errors": [
{
"message": "Argument 'facultativeMark' on InputObject 'FacultativeMarkAttributes' is required. Expected type Int!",
"locations": [
{
"line": 2,
"column": 52
}
],
"path": [
"mutation addfacultativMark",
"addFacultativeMark",
"attributes",
"facultativeMark"
],
"extensions": {
"code": "missingRequiredInputObjectAttribute",
"argumentName": "facultativeMark",
"argumentType": "Int!",
"inputObjectType": "FacultativeMarkAttributes"
}
}
]
}
Answer the question
In order to leave comments, you need to log in
One option is to collect the translation from the meta information that is in the error message. Bind to an error code as an identifier for localization
require "json"
require "i18n"
errors = JSON.parse(<<~JSON, symbolize_names: true)[:errors]
{
"errors": [
{
"message": "Argument 'facultativeMark' on InputObject 'FacultativeMarkAttributes' is required. Expected type Int!",
"locations": [
{
"line": 2,
"column": 52
}
],
"path": [
"mutation addfacultativMark",
"addFacultativeMark",
"attributes",
"facultativeMark"
],
"extensions": {
"code": "missingRequiredInputObjectAttribute",
"argumentName": "facultativeMark",
"argumentType": "Int!",
"inputObjectType": "FacultativeMarkAttributes"
}
}
]
}
JSON
I18n.available_locales = [:ru]
I18n.locale = :ru
I18n.backend.store_translations(:ru, YAML.load(<<~YAML)["ru"])
ru:
external_api:
errors:
missingRequiredInputObjectAttribute: Аргумент '%{argumentName}' для '%{inputObjectType}' является обязательным. Ожидается тип '%{argumentType}'
YAML
errors.each do |error|
vars = error[:extensions].dup
code = vars.delete(:code)
error[:message_en] = error[:message]
error[:message] = I18n.t(code, scope: "external_api.errors", **vars)
end
pp errors
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question