Comments (1)
After some hints from @benjie and @RedShift1 on Discord and even more digging into the source, I've managed to get the following working (even if it's the opposite of @benjie's suggestion 😅):
module.exports = function i18nPlugin (builder) {
const isPrimaryKey = (table, attr) => table.primaryKeyConstraint && table.primaryKeyConstraint.keyAttributeNums.includes(attr.num)
, isForeignKey = (table, attr) => table.constraints.some(constraint => constraint.type === 'f' && constraint.keyAttributeNums.includes(attr.num));
builder.hook('GraphQLObjectType:fields', (
fields,
build,
context,
) => {
const {
pgSql: sql, inflection, pgColumnFilter, pgOmit: omit,
graphql: { GraphQLString },
pgGetSelectValueForFieldAndTypeAndModifier,
} = build;
const { scope, fieldWithHooks } = context;
const { pgIntrospection: table, isPgRowType, isPgCompoundType } = scope;
// Ensure we're only working on tables
if (!(isPgRowType || isPgCompoundType) || !table || table.kind !== 'class')
return fields;
// Filter out any fields we don't want to work with
const attributesToReplace = table.attributes
.filter(a => !( // Filter out if any are true:
!a.tags.i18n // Isn't translatable
|| !pgColumnFilter(a, build, context) // Isn't whatever this is
|| omit(a, 'read') // Isn't readable
|| isPrimaryKey(table, a) // Is a primary key
|| isForeignKey(table, a) // Is a foreign key
));
if (attributesToReplace.length === 0)
return fields;
const keyPrefix = `${table.namespace.name}.${table.name}`;
for (const attr of attributesToReplace) {
const fieldName = inflection.column(attr);
// Replace the existing field with a modified version of itself
fields[fieldName] = fieldWithHooks(
fieldName,
fieldContext => {
const { addDataGenerator } = fieldContext;
const column = sql.identifier(attr.name);
const key = `${keyPrefix}.${column.names.join('.')}`;
addDataGenerator(parsedResolveInfoFragment => ({
pgQuery: queryBuilder => {
const tableAlias = queryBuilder.getTableAlias();
// Note: You shouldn't modify `queryBuilder.data`
// directly, but we're doing it anyway
// @see https://github.com/graphile/graphile-engine/issues/368#issuecomment-450865101
// Filter out the existing select for this column
// by its alias...
queryBuilder.data.select = queryBuilder.data.select
.filter(s => s[1] !== parsedResolveInfoFragment.alias);
// ...and add our select in its place
queryBuilder.select(
pgGetSelectValueForFieldAndTypeAndModifier(
GraphQLString,
fieldContext,
parsedResolveInfoFragment,
sql.fragment`(coalesce((
select pairs
from ${sql.identifier('internal', 'i18n_pairs')}
where id = ${tableAlias}.${sql.identifier('id')}
and locale = util.preferred_locale()
)->>'${sql.raw(key)}', ${column}))`,
attr.type,
attr.typeModifier
),
parsedResolveInfoFragment.alias
);
},
}));
// Since we're not actually changing anything about the
// field (just how it's queried) we can return it like
// nothing happened...
return fields[fieldName];
},
{ pgFieldIntrospection: attr },
);
}
return fields;
}, ['PgColumns']);
};
While it does exactly what I want it to, it does have one major flaw. For each column we want to translate, we're having to do a sub-query to get the translated values. It would be much more performant to join the table instead. Unfortunately this isn't possible at the moment (see #368 (comment) and #2) even if we abuse queryBuilder.data.join
(which adds it to the sub-query with no way of selecting columns).
Since it's working I'm going to close this issue for now, but might come back to it if we notice any significant performance issues.
from graphile-engine.
Related Issues (20)
- Asynchronous builder hooks HOT 1
- Use collation in order by HOT 3
- GraphQL v16 HOT 6
- For some database schemas, PgIntrospectionPlugin.js abruptly crashes NodeJS (with --track-heap-objects flag, or memory profiling) HOT 5
- InitObject is typed wrong HOT 4
- [graphql-parse-resolve-info] Fix types or example HOT 3
- Custom functions for `nodeId` in `NodePlugin` HOT 2
- Add depth traversal to `simplifyParsedResolveInfoFragmentWithType` HOT 2
- No Way to Access Request From Resolvers? HOT 1
- [graphile-build]: Types for Build Don't Match Source HOT 4
- graphql-parse-resolve-info scalar fields HOT 2
- Pagination cursors not working for tables with at least one bigint component HOT 6
- graphile/subscriptions-lds does not trigger on DELETE if subscription contains only edges
- Project depends on vulnerable version of jsonwebtoken HOT 2
- graphql-parse-resolve-info - What to do to get the same output like graphql-fields? HOT 5
- Don't silently swallow exceptions in resolveNode HOT 2
- alias a column at mutation time only? HOT 2
- Type with array property triggers error HOT 10
- Error using PG client: "We only support PG clients from a PG pool..." HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from graphile-engine.