Skip to content

Instantly share code, notes, and snippets.

@SachaG
Last active December 11, 2020 08:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SachaG/dc6a1584acc2bdaaf35166abfe3145bc to your computer and use it in GitHub Desktop.
Save SachaG/dc6a1584acc2bdaaf35166abfe3145bc to your computer and use it in GitHub Desktop.
GraphQL Intl Directive
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