Skip to content

Instantly share code, notes, and snippets.

@hos
Last active March 3, 2021 17:44
Show Gist options
  • Save hos/4a4300cb1cb8ee734f2202704496771e to your computer and use it in GitHub Desktop.
Save hos/4a4300cb1cb8ee734f2202704496771e to your computer and use it in GitHub Desktop.
Postgraphile plugin to use table_name_locale to map translated data on original. NOTE this won't work for order by, filter or similar quries.
export default function LocalePlugin (builder) {
builder.hook('GraphQLObjectType:fields:field', (field, build, ctx) => {
const { pgSql: sql, inflection, options } = build
const {
scope: { pgFieldIntrospection },
addDataGenerator
} = ctx
if (
!pgFieldIntrospection ||
!pgFieldIntrospection.tags ||
!Object.keys(pgFieldIntrospection.tags).length ||
!pgFieldIntrospection.tags.localize
) {
return field
}
const tableName =
inflection.singularize(pgFieldIntrospection.class.name) + '_locales'
const columnName = pgFieldIntrospection.name
addDataGenerator(({ alias }) => {
return {
pgQuery (queryBuilder) {
const sub = Symbol('query')
const locale = queryBuilder.context.req.locale
queryBuilder.select(
() => sql.fragment`(
SELECT
${sql.identifier(sub, columnName)}
FROM ${sql.identifier(options.localesSchema, tableName)}
AS ${sql.identifier(sub)}
WHERE ${sql.identifier(sub, 'lang')} = ${sql.value(locale)}
AND ${sql.identifier(
sub,
'source_id'
)} = ${queryBuilder.getTableAlias()}.id
)`,
alias + `_${locale}`
)
}
}
})
return Object.assign(field, {
async resolve (source, args, context, info) {
const locale = context.req.locale
const key = `${info.fieldName}_${locale}`
return source[key]
}
})
})
}
@ken0x0a
Copy link

ken0x0a commented Dec 27, 2019

Thank you for the answer at Discord!

I didn't expect this super elegant solution.
I should definitely read source code of postgraphile...

Thank you a lot!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment