P
P
Procyon2021-10-04 09:46:50
Ruby on Rails
Procyon, 2021-10-04 09:46:50

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

I need to translate, apparently, the message field and, preferably, use rail internationalization for this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vsuhachev, 2021-10-05
@vsuhachev

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 question

Ask a Question

731 491 924 answers to any question