Last active
December 11, 2020 08:49
-
-
Save SachaG/dc6a1584acc2bdaaf35166abfe3145bc to your computer and use it in GitHub Desktop.
GraphQL Intl Directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class IntlDirective extends SchemaDirectiveVisitor { | |
visitFieldDefinition(field, details) { | |
const fieldName = field.name; | |
field.resolve = async function (...args) { | |
// get document, GraphQL arguments, and query context | |
const [ doc, graphQLArguments, context ] = args; | |
// get the locale either from the query's arguments, or from the context | |
const locale = graphQLArguments.locale || context.locale; | |
// get the field containing translations | |
const intlField = doc[`${name}_intl`]; | |
// Return string in requested or default language, or else field's original value | |
return intlField && getLocaleString(intlField, locale) || doc[fieldName]; | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment