graphile-i18n 0.0.2 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +3 -1
- package/README.md +128 -34
- package/env.d.ts +5 -0
- package/env.js +17 -0
- package/esm/env.js +14 -0
- package/esm/index.js +5 -0
- package/esm/middleware.js +57 -0
- package/esm/plugin.js +147 -0
- package/index.d.ts +5 -0
- package/index.js +15 -0
- package/middleware.d.ts +26 -0
- package/middleware.js +65 -0
- package/package.json +33 -56
- package/plugin.d.ts +10 -0
- package/plugin.js +153 -0
- package/main/env.js +0 -22
- package/main/index.js +0 -37
- package/main/middleware.js +0 -95
- package/main/plugin.js +0 -206
- package/module/env.js +0 -9
- package/module/index.js +0 -4
- package/module/middleware.js +0 -60
- package/module/plugin.js +0 -173
package/LICENSE
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
The MIT License (MIT)
|
|
2
2
|
|
|
3
|
-
Copyright (c)
|
|
3
|
+
Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
|
|
4
|
+
Copyright (c) 2025 Hyperweb <developers@hyperweb.io>
|
|
5
|
+
Copyright (c) 2020-present, Interweb, Inc.
|
|
4
6
|
|
|
5
7
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
8
|
of this software and associated documentation files (the "Software"), to deal
|
package/README.md
CHANGED
|
@@ -1,59 +1,153 @@
|
|
|
1
|
-
# graphile-i18n
|
|
1
|
+
# graphile-i18n
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
<p align="center" width="100%">
|
|
4
|
+
<img height="250" src="https://raw.githubusercontent.com/launchql/launchql/refs/heads/main/assets/outline-logo.svg" />
|
|
5
|
+
</p>
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
<p align="center" width="100%">
|
|
8
|
+
<a href="https://github.com/launchql/launchql/actions/workflows/run-tests.yaml">
|
|
9
|
+
<img height="20" src="https://github.com/launchql/launchql/actions/workflows/run-tests.yaml/badge.svg" />
|
|
10
|
+
</a>
|
|
11
|
+
<a href="https://github.com/launchql/launchql/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
|
|
12
|
+
</p>
|
|
8
13
|
|
|
9
|
-
|
|
14
|
+
TypeScript rewrite of the Graphile/PostGraphile i18n plugin. Adds language-aware fields sourced from translation tables declared via smart comments.
|
|
10
15
|
|
|
11
|
-
|
|
12
|
-
2. Add smart comments
|
|
13
|
-
3. Register plugin with postgraphile
|
|
16
|
+
## Install
|
|
14
17
|
|
|
15
|
-
|
|
18
|
+
```bash
|
|
19
|
+
pnpm add graphile-i18n
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Usage
|
|
16
23
|
|
|
17
|
-
Add
|
|
24
|
+
1. Add a translation table and tag the base table with `@i18n`:
|
|
18
25
|
|
|
19
26
|
```sql
|
|
20
27
|
CREATE TABLE app_public.projects (
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
28
|
+
id serial PRIMARY KEY,
|
|
29
|
+
name citext,
|
|
30
|
+
description citext
|
|
24
31
|
);
|
|
25
32
|
COMMENT ON TABLE app_public.projects IS E'@i18n project_language_variations';
|
|
26
33
|
|
|
27
34
|
CREATE TABLE app_public.project_language_variations (
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
35
|
+
id serial PRIMARY KEY,
|
|
36
|
+
project_id int NOT NULL REFERENCES app_public.projects(id),
|
|
37
|
+
lang_code citext,
|
|
38
|
+
name citext,
|
|
39
|
+
description citext,
|
|
40
|
+
UNIQUE (project_id, lang_code)
|
|
34
41
|
);
|
|
35
42
|
```
|
|
36
43
|
|
|
37
|
-
|
|
44
|
+
2. Register the plugin:
|
|
38
45
|
|
|
39
|
-
```
|
|
46
|
+
```ts
|
|
47
|
+
import express from 'express';
|
|
48
|
+
import { postgraphile } from 'postgraphile';
|
|
49
|
+
import {
|
|
50
|
+
LangPlugin,
|
|
51
|
+
additionalGraphQLContextFromRequest,
|
|
52
|
+
} from 'graphile-i18n';
|
|
53
|
+
|
|
54
|
+
const app = express();
|
|
40
55
|
app.use(
|
|
41
|
-
postgraphile(
|
|
42
|
-
appendPlugins: [
|
|
43
|
-
LangPlugin
|
|
44
|
-
],
|
|
56
|
+
postgraphile(process.env.DATABASE_URL, ['app_public'], {
|
|
57
|
+
appendPlugins: [LangPlugin],
|
|
45
58
|
graphileBuildOptions: {
|
|
46
|
-
langPluginDefaultLanguages: ['en']
|
|
47
|
-
}
|
|
59
|
+
langPluginDefaultLanguages: ['en'],
|
|
60
|
+
},
|
|
61
|
+
additionalGraphQLContextFromRequest,
|
|
48
62
|
})
|
|
49
63
|
);
|
|
50
64
|
```
|
|
51
65
|
|
|
52
|
-
|
|
66
|
+
Requests with `Accept-Language` headers receive the closest translation; fields fall back to the base table values when a translation is missing.
|
|
67
|
+
|
|
68
|
+
## Tests
|
|
53
69
|
|
|
70
|
+
Tests run against a real Postgres instance using `graphile-test`:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
pnpm test
|
|
54
74
|
```
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
75
|
+
|
|
76
|
+
Ensure Postgres is available at `postgres://postgres:password@localhost:5432`.
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## Education and Tutorials
|
|
81
|
+
|
|
82
|
+
1. 🚀 [Quickstart: Getting Up and Running](https://launchql.com/learn/quickstart)
|
|
83
|
+
Get started with modular databases in minutes. Install prerequisites and deploy your first module.
|
|
84
|
+
|
|
85
|
+
2. 📦 [Modular PostgreSQL Development with Database Packages](https://launchql.com/learn/modular-postgres)
|
|
86
|
+
Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
|
|
87
|
+
|
|
88
|
+
3. ✏️ [Authoring Database Changes](https://launchql.com/learn/authoring-database-changes)
|
|
89
|
+
Master the workflow for adding, organizing, and managing database changes with pgpm.
|
|
90
|
+
|
|
91
|
+
4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://launchql.com/learn/e2e-postgres-testing)
|
|
92
|
+
Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
|
|
93
|
+
|
|
94
|
+
5. ⚡ [Supabase Testing](https://launchql.com/learn/supabase)
|
|
95
|
+
Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
|
|
96
|
+
|
|
97
|
+
6. 💧 [Drizzle ORM Testing](https://launchql.com/learn/drizzle-testing)
|
|
98
|
+
Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
|
|
99
|
+
|
|
100
|
+
7. 🔧 [Troubleshooting](https://launchql.com/learn/troubleshooting)
|
|
101
|
+
Common issues and solutions for pgpm, PostgreSQL, and testing.
|
|
102
|
+
|
|
103
|
+
## Related LaunchQL Tooling
|
|
104
|
+
|
|
105
|
+
### 🧪 Testing
|
|
106
|
+
|
|
107
|
+
* [launchql/pgsql-test](https://github.com/launchql/launchql/tree/main/packages/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
|
|
108
|
+
* [launchql/supabase-test](https://github.com/launchql/launchql/tree/main/packages/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
|
|
109
|
+
* [launchql/graphile-test](https://github.com/launchql/launchql/tree/main/packages/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
|
|
110
|
+
* [launchql/pg-query-context](https://github.com/launchql/launchql/tree/main/packages/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
|
|
111
|
+
|
|
112
|
+
### 🧠 Parsing & AST
|
|
113
|
+
|
|
114
|
+
* [launchql/pgsql-parser](https://github.com/launchql/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
|
|
115
|
+
* [launchql/libpg-query-node](https://github.com/launchql/libpg-query-node): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
|
|
116
|
+
* [launchql/pg-proto-parser](https://github.com/launchql/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
|
|
117
|
+
* [@pgsql/enums](https://github.com/launchql/pgsql-parser/tree/main/packages/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
|
|
118
|
+
* [@pgsql/types](https://github.com/launchql/pgsql-parser/tree/main/packages/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
|
|
119
|
+
* [@pgsql/utils](https://github.com/launchql/pgsql-parser/tree/main/packages/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
|
|
120
|
+
* [launchql/pg-ast](https://github.com/launchql/launchql/tree/main/packages/pg-ast): **🔍 Low-level AST tools** and transformations for Postgres query structures.
|
|
121
|
+
|
|
122
|
+
### 🚀 API & Dev Tools
|
|
123
|
+
|
|
124
|
+
* [launchql/server](https://github.com/launchql/launchql/tree/main/packages/server): **⚡ Express-based API server** powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
|
|
125
|
+
* [launchql/explorer](https://github.com/launchql/launchql/tree/main/packages/explorer): **🔎 Visual API explorer** with GraphiQL for browsing across all databases and schemas—useful for debugging, documentation, and API prototyping.
|
|
126
|
+
|
|
127
|
+
### 🔁 Streaming & Uploads
|
|
128
|
+
|
|
129
|
+
* [launchql/s3-streamer](https://github.com/launchql/launchql/tree/main/packages/s3-streamer): **📤 Direct S3 streaming** for large files with support for metadata injection and content validation.
|
|
130
|
+
* [launchql/etag-hash](https://github.com/launchql/launchql/tree/main/packages/etag-hash): **🏷️ S3-compatible ETags** created by streaming and hashing file uploads in chunks.
|
|
131
|
+
* [launchql/etag-stream](https://github.com/launchql/launchql/tree/main/packages/etag-stream): **🔄 ETag computation** via Node stream transformer during upload or transfer.
|
|
132
|
+
* [launchql/uuid-hash](https://github.com/launchql/launchql/tree/main/packages/uuid-hash): **🆔 Deterministic UUIDs** generated from hashed content, great for deduplication and asset referencing.
|
|
133
|
+
* [launchql/uuid-stream](https://github.com/launchql/launchql/tree/main/packages/uuid-stream): **🌊 Streaming UUID generation** based on piped file content—ideal for upload pipelines.
|
|
134
|
+
* [launchql/upload-names](https://github.com/launchql/launchql/tree/main/packages/upload-names): **📂 Collision-resistant filenames** utility for structured and unique file names for uploads.
|
|
135
|
+
|
|
136
|
+
### 🧰 CLI & Codegen
|
|
137
|
+
|
|
138
|
+
* [pgpm](https://github.com/launchql/launchql/tree/main/packages/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
|
|
139
|
+
* [@launchql/cli](https://github.com/launchql/launchql/tree/main/packages/cli): **🖥️ Command-line toolkit** for managing LaunchQL projects—supports database scaffolding, migrations, seeding, code generation, and automation.
|
|
140
|
+
* [launchql/launchql-gen](https://github.com/launchql/launchql/tree/main/packages/launchql-gen): **✨ Auto-generated GraphQL** mutations and queries dynamically built from introspected schema data.
|
|
141
|
+
* [@launchql/query-builder](https://github.com/launchql/launchql/tree/main/packages/query-builder): **🏗️ SQL constructor** providing a robust TypeScript-based query builder for dynamic generation of `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and stored procedure calls—supports advanced SQL features like `JOIN`, `GROUP BY`, and schema-qualified queries.
|
|
142
|
+
* [@launchql/query](https://github.com/launchql/launchql/tree/main/packages/query): **🧩 Fluent GraphQL builder** for PostGraphile schemas. ⚡ Schema-aware via introspection, 🧩 composable and ergonomic for building deeply nested queries.
|
|
143
|
+
|
|
144
|
+
## Credits
|
|
145
|
+
|
|
146
|
+
🛠 Built by LaunchQL — if you like our tools, please checkout and contribute to [our github ⚛️](https://github.com/launchql)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
## Disclaimer
|
|
150
|
+
|
|
151
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
152
|
+
|
|
153
|
+
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
|
package/env.d.ts
ADDED
package/env.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.env = void 0;
|
|
4
|
+
const envalid_1 = require("envalid");
|
|
5
|
+
const commaSeparatedArray = (0, envalid_1.makeValidator)((value) => {
|
|
6
|
+
if (typeof value !== 'string') {
|
|
7
|
+
throw new Error('Expected a comma separated string');
|
|
8
|
+
}
|
|
9
|
+
return value
|
|
10
|
+
.split(',')
|
|
11
|
+
.map((entry) => entry.trim())
|
|
12
|
+
.filter(Boolean);
|
|
13
|
+
});
|
|
14
|
+
exports.env = (0, envalid_1.cleanEnv)(process.env, {
|
|
15
|
+
ACCEPTED_LANGUAGES: commaSeparatedArray({ default: ['en', 'es'] })
|
|
16
|
+
});
|
|
17
|
+
exports.default = exports.env;
|
package/esm/env.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { cleanEnv, makeValidator } from 'envalid';
|
|
2
|
+
const commaSeparatedArray = makeValidator((value) => {
|
|
3
|
+
if (typeof value !== 'string') {
|
|
4
|
+
throw new Error('Expected a comma separated string');
|
|
5
|
+
}
|
|
6
|
+
return value
|
|
7
|
+
.split(',')
|
|
8
|
+
.map((entry) => entry.trim())
|
|
9
|
+
.filter(Boolean);
|
|
10
|
+
});
|
|
11
|
+
export const env = cleanEnv(process.env, {
|
|
12
|
+
ACCEPTED_LANGUAGES: commaSeparatedArray({ default: ['en', 'es'] })
|
|
13
|
+
});
|
|
14
|
+
export default env;
|
package/esm/index.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import DataLoader from 'dataloader';
|
|
2
|
+
import langParser from 'accept-language-parser';
|
|
3
|
+
import env from './env';
|
|
4
|
+
const escapeIdentifier = (str) => `"${str.replace(/"/g, '""')}"`;
|
|
5
|
+
export const makeLanguageDataLoaderForTable = (_req) => {
|
|
6
|
+
const cache = new Map();
|
|
7
|
+
return (props, pgClient, languageCodes, identifier, idType, sqlField, gqlField) => {
|
|
8
|
+
let dataLoader = cache.get(props);
|
|
9
|
+
if (!dataLoader) {
|
|
10
|
+
const { table, coalescedFields, variationsTableName, key } = props;
|
|
11
|
+
const schemaName = escapeIdentifier(table.namespaceName);
|
|
12
|
+
const baseTable = escapeIdentifier(table.name);
|
|
13
|
+
const variationTable = escapeIdentifier(variationsTableName);
|
|
14
|
+
const joinKey = escapeIdentifier(key ?? identifier);
|
|
15
|
+
const fields = coalescedFields.join(', ');
|
|
16
|
+
const baseAlias = [schemaName, baseTable].join('.');
|
|
17
|
+
const variationAlias = [schemaName, variationTable].join('.');
|
|
18
|
+
dataLoader = new DataLoader(async (ids) => {
|
|
19
|
+
const { rows } = await pgClient.query(`
|
|
20
|
+
select *
|
|
21
|
+
from unnest($1::${idType}[]) ids(${identifier})
|
|
22
|
+
inner join lateral (
|
|
23
|
+
select b.${identifier}, v.${sqlField} as "${gqlField}", ${fields}
|
|
24
|
+
from ${baseAlias} b
|
|
25
|
+
left join ${variationAlias} v
|
|
26
|
+
on (v.${joinKey} = b.${identifier} and array_position($2, ${sqlField}) is not null)
|
|
27
|
+
where b.${identifier} = ids.${identifier}
|
|
28
|
+
order by array_position($2, ${sqlField}) asc nulls last
|
|
29
|
+
limit 1
|
|
30
|
+
) tmp on (true)
|
|
31
|
+
`, [ids, languageCodes]);
|
|
32
|
+
return ids.map((id) => rows.find((row) => row?.[identifier] === id));
|
|
33
|
+
});
|
|
34
|
+
cache.set(props, dataLoader);
|
|
35
|
+
}
|
|
36
|
+
return dataLoader;
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
const getAcceptLanguageHeader = (req) => {
|
|
40
|
+
if (!req)
|
|
41
|
+
return undefined;
|
|
42
|
+
const header = typeof req.get === 'function'
|
|
43
|
+
? req.get('accept-language')
|
|
44
|
+
: req.headers?.['accept-language'];
|
|
45
|
+
return Array.isArray(header) ? header.join(',') : header;
|
|
46
|
+
};
|
|
47
|
+
export const additionalGraphQLContextFromRequest = async (req, _res) => {
|
|
48
|
+
const acceptLanguage = getAcceptLanguageHeader(req);
|
|
49
|
+
const language = langParser.pick(env.ACCEPTED_LANGUAGES, acceptLanguage) ??
|
|
50
|
+
env.ACCEPTED_LANGUAGES[0];
|
|
51
|
+
const langCodes = language ? [language] : env.ACCEPTED_LANGUAGES;
|
|
52
|
+
return {
|
|
53
|
+
langCodes,
|
|
54
|
+
getLanguageDataLoader: makeLanguageDataLoaderForTable(req)
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
export default additionalGraphQLContextFromRequest;
|
package/esm/plugin.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { makeLanguageDataLoaderForTable } from './middleware';
|
|
2
|
+
const defaultLanguageLoaderFactory = makeLanguageDataLoaderForTable();
|
|
3
|
+
const escapeIdentifier = (str) => `"${str.replace(/"/g, '""')}"`;
|
|
4
|
+
const hasI18nTag = (table) => Object.prototype.hasOwnProperty.call(table.tags, 'i18n');
|
|
5
|
+
const getPrimaryKeyInfo = (table) => {
|
|
6
|
+
const identifier = table.primaryKeyConstraint?.keyAttributes?.[0]?.name;
|
|
7
|
+
const idType = table.primaryKeyConstraint?.keyAttributes?.[0]?.type?.name;
|
|
8
|
+
return { identifier, idType };
|
|
9
|
+
};
|
|
10
|
+
export const LangPlugin = (builder, options) => {
|
|
11
|
+
const { langPluginLanguageCodeColumn = 'lang_code', langPluginLanguageCodeGqlField = 'langCode', langPluginAllowedTypes = ['citext', 'text'], langPluginDefaultLanguages = ['en'] } = options;
|
|
12
|
+
builder.hook('build', (build) => {
|
|
13
|
+
const introspection = build.pgIntrospectionResultsByKind;
|
|
14
|
+
const inflection = build.inflection;
|
|
15
|
+
const tablesWithLanguageTables = introspection.class.filter(hasI18nTag);
|
|
16
|
+
const tablesWithLanguageTablesIdInfo = tablesWithLanguageTables.reduce((memo, table) => {
|
|
17
|
+
const keyInfo = getPrimaryKeyInfo(table);
|
|
18
|
+
if (table.tags.i18n) {
|
|
19
|
+
memo[table.tags.i18n] = keyInfo;
|
|
20
|
+
}
|
|
21
|
+
return memo;
|
|
22
|
+
}, {});
|
|
23
|
+
const languageVariationTables = tablesWithLanguageTables.map((table) => introspection.class.find((candidate) => candidate.name === table.tags.i18n &&
|
|
24
|
+
candidate.namespaceName === table.namespaceName));
|
|
25
|
+
const i18nTables = {};
|
|
26
|
+
const tables = {};
|
|
27
|
+
tablesWithLanguageTables.forEach((table) => {
|
|
28
|
+
const i18nTableName = table.tags.i18n;
|
|
29
|
+
i18nTables[i18nTableName] = {
|
|
30
|
+
table: table.name,
|
|
31
|
+
key: null,
|
|
32
|
+
connection: inflection.connection(inflection.tableType(table)),
|
|
33
|
+
attrs: {},
|
|
34
|
+
fields: {},
|
|
35
|
+
keyInfo: tablesWithLanguageTablesIdInfo[i18nTableName] ?? {}
|
|
36
|
+
};
|
|
37
|
+
tables[table.name] = i18nTableName;
|
|
38
|
+
});
|
|
39
|
+
languageVariationTables.forEach((table) => {
|
|
40
|
+
if (!table)
|
|
41
|
+
return;
|
|
42
|
+
const foreignConstraintsThatMatter = table.constraints
|
|
43
|
+
.filter((constraint) => constraint.type === 'f')
|
|
44
|
+
.filter((constraint) => constraint.foreignClass.name === i18nTables[table.name].table);
|
|
45
|
+
if (foreignConstraintsThatMatter.length !== 1) {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const foreignKeyConstraint = foreignConstraintsThatMatter[0];
|
|
49
|
+
if (!foreignKeyConstraint || foreignKeyConstraint.keyAttributes.length !== 1) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
i18nTables[table.name].key = foreignKeyConstraint.keyAttributes[0].name;
|
|
53
|
+
const { identifier } = i18nTables[table.name].keyInfo;
|
|
54
|
+
if (!identifier)
|
|
55
|
+
return;
|
|
56
|
+
table.attributes.forEach((attr) => {
|
|
57
|
+
if ([langPluginLanguageCodeColumn, identifier].includes(attr.name))
|
|
58
|
+
return;
|
|
59
|
+
if (langPluginAllowedTypes.includes(attr.type.name)) {
|
|
60
|
+
i18nTables[table.name].fields[inflection.column(attr)] = {
|
|
61
|
+
type: attr.type.name,
|
|
62
|
+
attr: attr.name,
|
|
63
|
+
isNotNull: attr.isNotNull,
|
|
64
|
+
column: inflection.column(attr)
|
|
65
|
+
};
|
|
66
|
+
i18nTables[table.name].attrs[attr.name] = {
|
|
67
|
+
type: attr.type.name,
|
|
68
|
+
attr: attr.name,
|
|
69
|
+
column: inflection.column(attr)
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
return build.extend(build, { i18n: { i18nTables, tables } });
|
|
75
|
+
});
|
|
76
|
+
builder.hook('GraphQLObjectType:fields', (fields, build, context) => {
|
|
77
|
+
const { graphql: { GraphQLString, GraphQLObjectType, GraphQLNonNull }, i18n: { i18nTables, tables } } = build;
|
|
78
|
+
const { scope: { pgIntrospection: table, isPgRowType }, fieldWithHooks } = context;
|
|
79
|
+
if (!isPgRowType || !table || table.kind !== 'class') {
|
|
80
|
+
return fields;
|
|
81
|
+
}
|
|
82
|
+
const variationsTableName = tables[table.name];
|
|
83
|
+
if (!variationsTableName) {
|
|
84
|
+
return fields;
|
|
85
|
+
}
|
|
86
|
+
const i18nTable = i18nTables[variationsTableName];
|
|
87
|
+
const { identifier, idType } = i18nTable.keyInfo;
|
|
88
|
+
if (!identifier || !idType) {
|
|
89
|
+
return fields;
|
|
90
|
+
}
|
|
91
|
+
const { key, fields: i18nFields } = i18nTable;
|
|
92
|
+
const localeFieldName = 'localeStrings';
|
|
93
|
+
const localeFieldsConfig = Object.keys(i18nFields).reduce((memo, field) => {
|
|
94
|
+
memo[field] = {
|
|
95
|
+
type: i18nFields[field].isNotNull
|
|
96
|
+
? new GraphQLNonNull(GraphQLString)
|
|
97
|
+
: GraphQLString,
|
|
98
|
+
description: `Locale for ${field}`
|
|
99
|
+
};
|
|
100
|
+
return memo;
|
|
101
|
+
}, {
|
|
102
|
+
langCode: {
|
|
103
|
+
type: GraphQLString
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
const localeFieldsType = new GraphQLObjectType({
|
|
107
|
+
name: `${context.Self.name}LocaleStrings`,
|
|
108
|
+
description: `Locales for ${context.Self.name}`,
|
|
109
|
+
fields: localeFieldsConfig
|
|
110
|
+
});
|
|
111
|
+
return build.extend(fields, {
|
|
112
|
+
[localeFieldName]: fieldWithHooks(localeFieldName, (fieldContext) => {
|
|
113
|
+
const { addDataGenerator } = fieldContext;
|
|
114
|
+
addDataGenerator(() => ({
|
|
115
|
+
pgQuery: (queryBuilder) => {
|
|
116
|
+
queryBuilder.select(build.pgSql.fragment `${queryBuilder.getTableAlias()}.${build.pgSql.identifier(identifier)}`, identifier);
|
|
117
|
+
}
|
|
118
|
+
}));
|
|
119
|
+
const coalescedFields = Object.keys(i18nFields).map((field) => {
|
|
120
|
+
const columnName = i18nFields[field].attr;
|
|
121
|
+
const escColumnName = escapeIdentifier(columnName);
|
|
122
|
+
const escFieldName = escapeIdentifier(field);
|
|
123
|
+
return `coalesce(v.${escColumnName}, b.${escColumnName}) as ${escFieldName}`;
|
|
124
|
+
});
|
|
125
|
+
const props = {
|
|
126
|
+
table,
|
|
127
|
+
coalescedFields,
|
|
128
|
+
variationsTableName,
|
|
129
|
+
key
|
|
130
|
+
};
|
|
131
|
+
return {
|
|
132
|
+
description: `Locales for ${context.Self.name}`,
|
|
133
|
+
type: new GraphQLNonNull(localeFieldsType),
|
|
134
|
+
async resolve(source, _args, gqlContext) {
|
|
135
|
+
const languageCodes = gqlContext.langCodes ?? langPluginDefaultLanguages;
|
|
136
|
+
const getLoader = gqlContext.getLanguageDataLoader ??
|
|
137
|
+
defaultLanguageLoaderFactory;
|
|
138
|
+
const dataloader = getLoader(props, gqlContext.pgClient, languageCodes, identifier, idType, langPluginLanguageCodeColumn, langPluginLanguageCodeGqlField);
|
|
139
|
+
return dataloader.load(source.id);
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
}, 'Adding the language code field from the lang plugin')
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
};
|
|
146
|
+
export { additionalGraphQLContextFromRequest, makeLanguageDataLoaderForTable } from './middleware';
|
|
147
|
+
export default LangPlugin;
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import LangPlugin from './plugin';
|
|
2
|
+
export { LangPlugin, type LangPluginOptions } from './plugin';
|
|
3
|
+
export { additionalGraphQLContextFromRequest, makeLanguageDataLoaderForTable, type I18nGraphQLContext, type I18nRequestLike, type LanguageDataLoaderFactory } from './middleware';
|
|
4
|
+
export { env } from './env';
|
|
5
|
+
export default LangPlugin;
|
package/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.env = exports.makeLanguageDataLoaderForTable = exports.additionalGraphQLContextFromRequest = exports.LangPlugin = void 0;
|
|
7
|
+
const plugin_1 = __importDefault(require("./plugin"));
|
|
8
|
+
var plugin_2 = require("./plugin");
|
|
9
|
+
Object.defineProperty(exports, "LangPlugin", { enumerable: true, get: function () { return plugin_2.LangPlugin; } });
|
|
10
|
+
var middleware_1 = require("./middleware");
|
|
11
|
+
Object.defineProperty(exports, "additionalGraphQLContextFromRequest", { enumerable: true, get: function () { return middleware_1.additionalGraphQLContextFromRequest; } });
|
|
12
|
+
Object.defineProperty(exports, "makeLanguageDataLoaderForTable", { enumerable: true, get: function () { return middleware_1.makeLanguageDataLoaderForTable; } });
|
|
13
|
+
var env_1 = require("./env");
|
|
14
|
+
Object.defineProperty(exports, "env", { enumerable: true, get: function () { return env_1.env; } });
|
|
15
|
+
exports.default = plugin_1.default;
|
package/middleware.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import DataLoader from 'dataloader';
|
|
2
|
+
import type { IncomingHttpHeaders } from 'http';
|
|
3
|
+
import type { PoolClient } from 'pg';
|
|
4
|
+
export interface LanguageLoaderProps {
|
|
5
|
+
table: {
|
|
6
|
+
name: string;
|
|
7
|
+
namespaceName: string;
|
|
8
|
+
};
|
|
9
|
+
coalescedFields: string[];
|
|
10
|
+
variationsTableName: string;
|
|
11
|
+
key: string | null;
|
|
12
|
+
}
|
|
13
|
+
export type LanguageRow = Record<string, unknown>;
|
|
14
|
+
export type LanguageDataLoader = DataLoader<string | number, LanguageRow | undefined>;
|
|
15
|
+
export type LanguageDataLoaderFactory = (props: LanguageLoaderProps, pgClient: PoolClient, languageCodes: readonly string[], identifier: string, idType: string, sqlField: string, gqlField: string) => LanguageDataLoader;
|
|
16
|
+
export interface I18nRequestLike {
|
|
17
|
+
get?: (header: string) => string | undefined;
|
|
18
|
+
headers?: IncomingHttpHeaders;
|
|
19
|
+
}
|
|
20
|
+
export interface I18nGraphQLContext {
|
|
21
|
+
langCodes: string[];
|
|
22
|
+
getLanguageDataLoader: LanguageDataLoaderFactory;
|
|
23
|
+
}
|
|
24
|
+
export declare const makeLanguageDataLoaderForTable: (_req?: I18nRequestLike) => LanguageDataLoaderFactory;
|
|
25
|
+
export declare const additionalGraphQLContextFromRequest: (req?: I18nRequestLike, _res?: unknown) => Promise<I18nGraphQLContext>;
|
|
26
|
+
export default additionalGraphQLContextFromRequest;
|
package/middleware.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.additionalGraphQLContextFromRequest = exports.makeLanguageDataLoaderForTable = void 0;
|
|
7
|
+
const dataloader_1 = __importDefault(require("dataloader"));
|
|
8
|
+
const accept_language_parser_1 = __importDefault(require("accept-language-parser"));
|
|
9
|
+
const env_1 = __importDefault(require("./env"));
|
|
10
|
+
const escapeIdentifier = (str) => `"${str.replace(/"/g, '""')}"`;
|
|
11
|
+
const makeLanguageDataLoaderForTable = (_req) => {
|
|
12
|
+
const cache = new Map();
|
|
13
|
+
return (props, pgClient, languageCodes, identifier, idType, sqlField, gqlField) => {
|
|
14
|
+
let dataLoader = cache.get(props);
|
|
15
|
+
if (!dataLoader) {
|
|
16
|
+
const { table, coalescedFields, variationsTableName, key } = props;
|
|
17
|
+
const schemaName = escapeIdentifier(table.namespaceName);
|
|
18
|
+
const baseTable = escapeIdentifier(table.name);
|
|
19
|
+
const variationTable = escapeIdentifier(variationsTableName);
|
|
20
|
+
const joinKey = escapeIdentifier(key ?? identifier);
|
|
21
|
+
const fields = coalescedFields.join(', ');
|
|
22
|
+
const baseAlias = [schemaName, baseTable].join('.');
|
|
23
|
+
const variationAlias = [schemaName, variationTable].join('.');
|
|
24
|
+
dataLoader = new dataloader_1.default(async (ids) => {
|
|
25
|
+
const { rows } = await pgClient.query(`
|
|
26
|
+
select *
|
|
27
|
+
from unnest($1::${idType}[]) ids(${identifier})
|
|
28
|
+
inner join lateral (
|
|
29
|
+
select b.${identifier}, v.${sqlField} as "${gqlField}", ${fields}
|
|
30
|
+
from ${baseAlias} b
|
|
31
|
+
left join ${variationAlias} v
|
|
32
|
+
on (v.${joinKey} = b.${identifier} and array_position($2, ${sqlField}) is not null)
|
|
33
|
+
where b.${identifier} = ids.${identifier}
|
|
34
|
+
order by array_position($2, ${sqlField}) asc nulls last
|
|
35
|
+
limit 1
|
|
36
|
+
) tmp on (true)
|
|
37
|
+
`, [ids, languageCodes]);
|
|
38
|
+
return ids.map((id) => rows.find((row) => row?.[identifier] === id));
|
|
39
|
+
});
|
|
40
|
+
cache.set(props, dataLoader);
|
|
41
|
+
}
|
|
42
|
+
return dataLoader;
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
exports.makeLanguageDataLoaderForTable = makeLanguageDataLoaderForTable;
|
|
46
|
+
const getAcceptLanguageHeader = (req) => {
|
|
47
|
+
if (!req)
|
|
48
|
+
return undefined;
|
|
49
|
+
const header = typeof req.get === 'function'
|
|
50
|
+
? req.get('accept-language')
|
|
51
|
+
: req.headers?.['accept-language'];
|
|
52
|
+
return Array.isArray(header) ? header.join(',') : header;
|
|
53
|
+
};
|
|
54
|
+
const additionalGraphQLContextFromRequest = async (req, _res) => {
|
|
55
|
+
const acceptLanguage = getAcceptLanguageHeader(req);
|
|
56
|
+
const language = accept_language_parser_1.default.pick(env_1.default.ACCEPTED_LANGUAGES, acceptLanguage) ??
|
|
57
|
+
env_1.default.ACCEPTED_LANGUAGES[0];
|
|
58
|
+
const langCodes = language ? [language] : env_1.default.ACCEPTED_LANGUAGES;
|
|
59
|
+
return {
|
|
60
|
+
langCodes,
|
|
61
|
+
getLanguageDataLoader: (0, exports.makeLanguageDataLoaderForTable)(req)
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
exports.additionalGraphQLContextFromRequest = additionalGraphQLContextFromRequest;
|
|
65
|
+
exports.default = exports.additionalGraphQLContextFromRequest;
|