Last active
March 3, 2021 17:44
-
-
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.
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
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] | |
} | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!!