-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathplugin.ts
More file actions
331 lines (287 loc) · 13.7 KB
/
Copy pathplugin.ts
File metadata and controls
331 lines (287 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/**
* PostGraphile v5 i18n Plugin
*
* Discovers tables tagged with @i18n and adds a `localeStrings` field to the
* base type. The field resolves the best-matching translation row based on
* language codes provided in the GraphQL context, falling back to the base
* table's own values when no translation exists.
*
* Smart tag format:
* COMMENT ON TABLE app_public.posts IS E'@i18n posts_translations';
*
* The value of @i18n is the name of the translation table in the same schema.
* The translation table must have:
* - A FK column referencing the base table's PK
* - A lang_code column (configurable)
* - UNIQUE(fk_column, lang_code)
* - One or more text/citext columns matching the base table's columns
*/
import 'graphile-build';
import 'graphile-build-pg';
import { TYPES } from '@dataplan/pg';
import type { PgCodecWithAttributes } from '@dataplan/pg';
import { QuoteUtils } from '@pgsql/quotes';
import { context as grafastContext, lambda, object } from 'grafast';
import type { GraphileConfig } from 'graphile-config';
import type { I18nPluginOptions, I18nTableInfo, TranslatableField } from './types';
// ─── Namespace Augmentations ─────────────────────────────────────────────────
declare global {
namespace GraphileConfig {
interface Plugins {
I18nPlugin: true;
}
}
}
// ─── Helpers ─────────────────────────────────────────────────────────────────
function hasI18nTag(codec: PgCodecWithAttributes): string | false {
const tags = (codec.extensions as any)?.tags;
if (!tags) return false;
const val = tags.i18n;
if (typeof val === 'string' && val.length > 0) return val;
return false;
}
function resolvePgTypeName(codec: any): string {
if (codec === TYPES.uuid) return 'uuid';
if (codec === TYPES.int) return 'int4';
if (codec === TYPES.bigint) return 'int8';
if (codec === TYPES.text) return 'text';
if (codec === TYPES.varchar) return 'text';
return codec?.name ?? 'text';
}
function resolveAttrPgType(codec: any): string {
if (codec === TYPES.text) return 'text';
if (codec === TYPES.varchar) return 'text';
if (codec?.name === 'citext') return 'citext';
return codec?.name ?? 'text';
}
// ─── Plugin Factory ──────────────────────────────────────────────────────────
export function createI18nPlugin(options: I18nPluginOptions = {}): GraphileConfig.Plugin {
const {
langCodeColumn = 'lang_code',
langCodeGqlField = 'langCode',
allowedTypes = ['text', 'citext'],
defaultLanguages = ['en'],
} = options;
// Closure-scoped state shared between init and field hooks
let i18nRegistry: Record<string, I18nTableInfo> = {};
let localeTypeCache: Record<string, any> = {};
return {
name: 'I18nPlugin',
version: '1.0.0',
schema: {
hooks: {
init: {
callback(_, build) {
i18nRegistry = {};
localeTypeCache = {};
for (const [, codec] of Object.entries(build.input.pgRegistry.pgCodecs)) {
const c = codec as PgCodecWithAttributes;
if (!c.attributes) continue;
const translationTableName = hasI18nTag(c);
if (!translationTableName) continue;
// Get schema name from the codec's pg extensions
let schemaName = (c.extensions as any)?.pg?.schemaName ?? 'public';
let pkColumn: string | null = null;
let pkType = 'text';
for (const [, resource] of Object.entries(build.input.pgRegistry.pgResources)) {
const r = resource as any;
if (r.codec === c) {
// Try multiple sources for schema name
const rSchema = r.extensions?.pg?.schemaName ?? r.schemaName;
if (rSchema) schemaName = rSchema;
// Extract PK from the resource's uniques array
const uniques = r.uniques as Array<{ attributes: string[]; isPrimary?: boolean }> | undefined;
if (uniques) {
const pk = uniques.find((u: any) => u.isPrimary);
if (pk && pk.attributes.length === 1) {
pkColumn = pk.attributes[0];
const pkAttr = c.attributes[pkColumn];
if (pkAttr) {
pkType = resolvePgTypeName((pkAttr as any).codec);
}
}
}
break;
}
}
if (!pkColumn) continue;
// Find the translation codec. The @i18n tag value is the SQL table name
// (e.g. 'posts_translations'), but PostGraphile inflects codec names
// to camelCase (e.g. 'postsTranslations'). Match via resource name.
let translationCodec: PgCodecWithAttributes | null = null;
for (const [, resource] of Object.entries(build.input.pgRegistry.pgResources)) {
const r = resource as any;
if (!r.codec?.attributes) continue;
// Match by the resource's SQL name (which preserves snake_case)
const sqlName = r.codec?.extensions?.pg?.name ?? r.name;
if (sqlName === translationTableName) {
translationCodec = r.codec as PgCodecWithAttributes;
break;
}
}
// Fallback: try matching the inflected codec name directly
if (!translationCodec) {
const inflectedName = build.inflection.camelCase(translationTableName);
for (const [, tCodec] of Object.entries(build.input.pgRegistry.pgCodecs)) {
const tc = tCodec as any;
if (!tc.attributes) continue;
if (tc.name === translationTableName || tc.name === inflectedName) {
translationCodec = tc;
break;
}
}
}
if (!translationCodec) continue;
// Find FK column on translation table — convention first, then type match
let fkColumn: string | null = null;
const conventionalFk = `${c.name}_id`;
if (translationCodec.attributes[conventionalFk]) {
fkColumn = conventionalFk;
}
if (!fkColumn) {
// Fallback: find a column with the same type as the PK, excluding
// common non-FK columns (id, lang_code)
for (const [attrName, attr] of Object.entries(translationCodec.attributes)) {
if (attrName === 'id' || attrName === langCodeColumn) continue;
const a = attr as any;
if (a.codec === (c.attributes[pkColumn] as any).codec) {
fkColumn = attrName;
break;
}
}
}
if (!fkColumn) continue;
// Discover translatable fields
const fields: Record<string, TranslatableField> = {};
for (const [attrName, attr] of Object.entries(translationCodec.attributes)) {
if (attrName === langCodeColumn || attrName === fkColumn) continue;
if (attrName === 'id' || attrName === 'created_at' || attrName === 'updated_at') continue;
const pgType = resolveAttrPgType((attr as any).codec);
if (!allowedTypes.includes(pgType)) continue;
const gqlName = build.inflection.camelCase(attrName);
fields[gqlName] = {
column: attrName,
type: pgType,
isNotNull: !!(attr as any).notNull,
};
}
if (Object.keys(fields).length === 0) continue;
i18nRegistry[c.name] = {
baseTable: c.name,
translationTable: translationTableName,
schemaName,
fkColumn,
pkColumn,
pkType,
fields,
};
}
return _;
},
},
GraphQLObjectType_fields(fields, build, context) {
const { graphql: { GraphQLString, GraphQLObjectType, GraphQLNonNull } } = build;
const { scope } = context;
if (!scope.pgCodec || !scope.isPgClassType) return fields;
const codec = scope.pgCodec as PgCodecWithAttributes;
const info = i18nRegistry[codec.name];
if (!info) return fields;
const localeFieldsConfig: Record<string, any> = {
[langCodeGqlField]: { type: GraphQLString },
};
for (const [gqlName, field] of Object.entries(info.fields)) {
localeFieldsConfig[gqlName] = {
type: field.isNotNull ? new GraphQLNonNull(GraphQLString) : GraphQLString,
};
}
const localeTypeName = `${build.inflection.tableType(codec)}LocaleStrings`;
if (!localeTypeCache[localeTypeName]) {
localeTypeCache[localeTypeName] = new GraphQLObjectType({
name: localeTypeName,
fields: localeFieldsConfig,
});
}
const localeType = localeTypeCache[localeTypeName];
const { schemaName, baseTable, translationTable, fkColumn, pkColumn, pkType, fields: i18nFields } = info;
// Identifier quoting via @pgsql/quotes (quote_ident semantics: quoted
// only when lexically required — uppercase, special chars, reserved
// keywords). Hashed multi-tenant schema names contain '-' so they are
// always emitted double-quoted, which schema-identifier rewriting at
// the pool seam relies on.
const qi = (name: string): string => QuoteUtils.quoteIdentifier(name);
const coalescedCols = Object.values(i18nFields)
.map(f => `coalesce(v.${qi(f.column)}, b.${qi(f.column)}) as ${qi(f.column)}`)
.join(', ');
const baseTableRef = QuoteUtils.quoteQualifiedIdentifier(schemaName, baseTable);
const translationTableRef = QuoteUtils.quoteQualifiedIdentifier(schemaName, translationTable);
// Build the SQL query template
const sqlQuery = `SELECT v.${qi(langCodeColumn)} AS "lang_code", ${coalescedCols}
FROM ${baseTableRef} b
LEFT JOIN ${translationTableRef} v
ON v.${qi(fkColumn)} = b.${qi(pkColumn)}
AND array_position($2::text[], v.${qi(langCodeColumn)}) IS NOT NULL
WHERE b.${qi(pkColumn)} = $1::${pkType}
ORDER BY array_position($2::text[], v.${qi(langCodeColumn)}) ASC NULLS LAST
LIMIT 1`;
// Build column names list for mapping base values
const baseColNames = Object.entries(i18nFields).map(([gqlName, f]) => ({
gqlName,
column: f.column,
}));
return build.extend(fields, {
localeStrings: {
type: new GraphQLNonNull(localeType),
plan($parent: any) {
// Extract PK and all base translatable columns from the parent row
const $id = $parent.get(pkColumn);
const $baseCols: Record<string, any> = {};
for (const { column } of baseColNames) {
$baseCols[column] = $parent.get(column);
}
const $withPgClient = (grafastContext() as any).get('withPgClient');
const $pgSettings = (grafastContext() as any).get('pgSettings');
const $langCodes = (grafastContext() as any).get('langCodes');
// Combine all inputs into a single step
const $input = object({
id: $id,
withPgClient: $withPgClient,
pgSettings: $pgSettings,
langCodes: $langCodes,
...$baseCols,
});
return lambda($input, async (input: any) => {
const { id, withPgClient, pgSettings, langCodes: ctxLangCodes, ...baseCols } = input;
const langs: string[] = ctxLangCodes ?? defaultLanguages;
if (!withPgClient || !id) {
const result: Record<string, any> = { [langCodeGqlField]: null };
for (const { gqlName, column } of baseColNames) {
result[gqlName] = baseCols[column] ?? null;
}
return result;
}
const row = await withPgClient(pgSettings, async (client: any) => {
const { rows } = await client.query(sqlQuery, [id, langs]);
return rows[0] ?? null;
});
if (!row) {
const result: Record<string, any> = { [langCodeGqlField]: null };
for (const { gqlName, column } of baseColNames) {
result[gqlName] = baseCols[column] ?? null;
}
return result;
}
const result: Record<string, any> = { [langCodeGqlField]: row.lang_code };
for (const { gqlName, column } of baseColNames) {
result[gqlName] = row[column] ?? null;
}
return result;
});
},
},
} as any, 'Adding i18n localeStrings field');
},
},
},
};
}
export const I18nPlugin = createI18nPlugin();