graphile-pg-type-mappings 0.2.0

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 ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Hyperweb <developers@hyperweb.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,234 @@
1
+ # graphile-pg-type-mappings
2
+
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
+
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">
12
+ <img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
13
+ </a>
14
+ <a href="https://www.npmjs.com/package/graphile-pg-type-mappings">
15
+ <img height="20" src="https://img.shields.io/github/package-json/v/launchql/launchql?filename=graphile%2Fgraphile-pg-type-mappings%2Fpackage.json"/>
16
+ </a>
17
+ </p>
18
+
19
+ Custom PostgreSQL type mappings plugin for Graphile/PostGraphile.
20
+
21
+ This plugin provides custom type mappings for PostgreSQL types to GraphQL types, including:
22
+
23
+ - `email` → `String`
24
+ - `hostname` → `String`
25
+ - `multiple_select` → `JSON`
26
+ - `single_select` → `JSON`
27
+ - `origin` → `String`
28
+ - `url` → `String`
29
+
30
+ > **Note:** If you need PostGIS types (like `geolocation` or `geopolygon` → `GeoJSON`), you can add them via `customTypeMappings` when using the PostGIS plugin.
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ npm install graphile-pg-type-mappings
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ### Basic Usage (Default Mappings)
41
+
42
+ ```typescript
43
+ import CustomPgTypeMappingsPlugin from 'graphile-pg-type-mappings';
44
+
45
+ const postgraphileOptions = {
46
+ appendPlugins: [CustomPgTypeMappingsPlugin],
47
+ // ... other options
48
+ };
49
+ ```
50
+
51
+ ### Custom Type Mappings
52
+
53
+ You can override default mappings or add new ones by passing options through `graphileBuildOptions`:
54
+
55
+ ```typescript
56
+ import CustomPgTypeMappingsPlugin from 'graphile-pg-type-mappings';
57
+
58
+ const postgraphileOptions = {
59
+ appendPlugins: [CustomPgTypeMappingsPlugin],
60
+ graphileBuildOptions: {
61
+ customTypeMappings: [
62
+ // Add a new custom type mapping
63
+ { name: 'my_custom_type', namespaceName: 'public', type: 'JSON' },
64
+ // Override an existing mapping (email -> JSON instead of String)
65
+ { name: 'email', namespaceName: 'public', type: 'JSON' }
66
+ ]
67
+ },
68
+ // ... other options
69
+ };
70
+ ```
71
+
72
+ ### Type Mapping Format
73
+
74
+ Each type mapping has the following structure:
75
+
76
+ ```typescript
77
+ interface TypeMapping {
78
+ name: string; // PostgreSQL type name
79
+ namespaceName: string; // PostgreSQL schema/namespace name (e.g., 'public')
80
+ type: string; // GraphQL type name (e.g., 'String', 'JSON', 'GeoJSON')
81
+ }
82
+ ```
83
+
84
+ ### Examples
85
+
86
+ #### Adding a Custom Type
87
+
88
+ ```typescript
89
+ const postgraphileOptions = {
90
+ appendPlugins: [CustomPgTypeMappingsPlugin],
91
+ graphileBuildOptions: {
92
+ customTypeMappings: [
93
+ { name: 'currency', namespaceName: 'public', type: 'String' },
94
+ { name: 'metadata', namespaceName: 'public', type: 'JSON' }
95
+ ]
96
+ }
97
+ };
98
+ ```
99
+
100
+ #### Overriding Default Mappings
101
+
102
+ ```typescript
103
+ const postgraphileOptions = {
104
+ appendPlugins: [CustomPgTypeMappingsPlugin],
105
+ graphileBuildOptions: {
106
+ customTypeMappings: [
107
+ // Override email to map to JSON instead of String
108
+ { name: 'email', namespaceName: 'public', type: 'JSON' }
109
+ ]
110
+ }
111
+ };
112
+ ```
113
+
114
+ #### Using Only Custom Mappings (No Defaults)
115
+
116
+ If you want to use only your custom mappings without the defaults, you can create a wrapper:
117
+
118
+ ```typescript
119
+ import CustomPgTypeMappingsPlugin, { TypeMapping } from 'graphile-pg-type-mappings';
120
+
121
+ const MyCustomPlugin = (builder: any) => {
122
+ return CustomPgTypeMappingsPlugin(builder, {
123
+ customTypeMappings: [
124
+ { name: 'my_type', namespaceName: 'public', type: 'String' }
125
+ ]
126
+ });
127
+ };
128
+
129
+ const postgraphileOptions = {
130
+ appendPlugins: [MyCustomPlugin],
131
+ // ... other options
132
+ };
133
+ ```
134
+
135
+ ## API
136
+
137
+ ### `CustomPgTypeMappingsPlugin`
138
+
139
+ The default export is a Graphile plugin that can be used directly or with custom options.
140
+
141
+ ### `TypeMapping`
142
+
143
+ ```typescript
144
+ interface TypeMapping {
145
+ name: string;
146
+ namespaceName: string;
147
+ type: string;
148
+ }
149
+ ```
150
+
151
+ ### `CustomPgTypeMappingsPluginOptions`
152
+
153
+ ```typescript
154
+ interface CustomPgTypeMappingsPluginOptions {
155
+ customTypeMappings?: TypeMapping[];
156
+ }
157
+ ```
158
+
159
+ ---
160
+
161
+ ## Education and Tutorials
162
+
163
+ 1. 🚀 [Quickstart: Getting Up and Running](https://launchql.com/learn/quickstart)
164
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
165
+
166
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://launchql.com/learn/modular-postgres)
167
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
168
+
169
+ 3. ✏️ [Authoring Database Changes](https://launchql.com/learn/authoring-database-changes)
170
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
171
+
172
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://launchql.com/learn/e2e-postgres-testing)
173
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
174
+
175
+ 5. ⚡ [Supabase Testing](https://launchql.com/learn/supabase)
176
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
177
+
178
+ 6. 💧 [Drizzle ORM Testing](https://launchql.com/learn/drizzle-testing)
179
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
180
+
181
+ 7. 🔧 [Troubleshooting](https://launchql.com/learn/troubleshooting)
182
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
183
+
184
+ ## Related LaunchQL Tooling
185
+
186
+ ### 🧪 Testing
187
+
188
+ * [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.
189
+ * [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.
190
+ * [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.
191
+ * [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.
192
+
193
+ ### 🧠 Parsing & AST
194
+
195
+ * [launchql/pgsql-parser](https://github.com/launchql/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
196
+ * [launchql/libpg-query-node](https://github.com/launchql/libpg-query-node): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
197
+ * [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.
198
+ * [@pgsql/enums](https://github.com/launchql/pgsql-parser/tree/main/packages/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
199
+ * [@pgsql/types](https://github.com/launchql/pgsql-parser/tree/main/packages/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
200
+ * [@pgsql/utils](https://github.com/launchql/pgsql-parser/tree/main/packages/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
201
+ * [launchql/pg-ast](https://github.com/launchql/launchql/tree/main/packages/pg-ast): **🔍 Low-level AST tools** and transformations for Postgres query structures.
202
+
203
+ ### 🚀 API & Dev Tools
204
+
205
+ * [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.
206
+ * [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.
207
+
208
+ ### 🔁 Streaming & Uploads
209
+
210
+ * [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.
211
+ * [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.
212
+ * [launchql/etag-stream](https://github.com/launchql/launchql/tree/main/packages/etag-stream): **🔄 ETag computation** via Node stream transformer during upload or transfer.
213
+ * [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.
214
+ * [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.
215
+ * [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.
216
+
217
+ ### 🧰 CLI & Codegen
218
+
219
+ * [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.
220
+ * [@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.
221
+ * [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.
222
+ * [@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.
223
+ * [@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.
224
+
225
+ ## Credits
226
+
227
+ 🛠 Built by LaunchQL — if you like our tools, please checkout and contribute to [our github ⚛️](https://github.com/launchql)
228
+
229
+
230
+ ## Disclaimer
231
+
232
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
233
+
234
+ 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/esm/index.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { Plugin } from 'graphile-build';
2
+ export interface TypeMapping {
3
+ name: string;
4
+ namespaceName: string;
5
+ type: string;
6
+ }
7
+ export interface CustomPgTypeMappingsPluginOptions {
8
+ /**
9
+ * Additional type mappings to add or override default mappings.
10
+ * Mappings are processed in order, so later mappings override earlier ones.
11
+ */
12
+ customTypeMappings?: TypeMapping[];
13
+ }
14
+ declare const CustomPgTypeMappingsPlugin: Plugin;
15
+ export default CustomPgTypeMappingsPlugin;
package/esm/index.js ADDED
@@ -0,0 +1,129 @@
1
+ const DEFAULT_MAPPINGS = [
2
+ { name: 'email', namespaceName: 'public', type: 'String' },
3
+ { name: 'hostname', namespaceName: 'public', type: 'String' },
4
+ { name: 'multiple_select', namespaceName: 'public', type: 'JSON' },
5
+ { name: 'single_select', namespaceName: 'public', type: 'JSON' },
6
+ { name: 'origin', namespaceName: 'public', type: 'String' },
7
+ { name: 'url', namespaceName: 'public', type: 'String' },
8
+ ];
9
+ const CustomPgTypeMappingsPlugin = (builder, options) => {
10
+ const opts = (options || {});
11
+ const customMappings = opts.customTypeMappings || [];
12
+ // Merge default mappings with custom mappings
13
+ // Custom mappings override defaults if they have the same name and namespaceName
14
+ const allMappings = [];
15
+ const seen = new Set();
16
+ // First add defaults
17
+ for (const mapping of DEFAULT_MAPPINGS) {
18
+ const key = `${mapping.namespaceName}.${mapping.name}`;
19
+ if (!seen.has(key)) {
20
+ allMappings.push(mapping);
21
+ seen.add(key);
22
+ }
23
+ }
24
+ // Then add/override with custom mappings
25
+ for (const mapping of customMappings) {
26
+ const key = `${mapping.namespaceName}.${mapping.name}`;
27
+ if (seen.has(key)) {
28
+ // Override existing mapping
29
+ const index = allMappings.findIndex(m => m.name === mapping.name && m.namespaceName === mapping.namespaceName);
30
+ if (index !== -1) {
31
+ allMappings[index] = mapping;
32
+ }
33
+ }
34
+ else {
35
+ // Add new mapping
36
+ allMappings.push(mapping);
37
+ seen.add(key);
38
+ }
39
+ }
40
+ // Store mappings for use in field resolver
41
+ const typeMappingsByTypeId = new Map();
42
+ builder.hook('build', (build, _context) => {
43
+ for (const { name, namespaceName, type } of allMappings) {
44
+ const pgType = build.pgIntrospectionResultsByKind.type.find(
45
+ // @ts-ignore
46
+ t => t.name === name && t.namespaceName === namespaceName);
47
+ if (pgType) {
48
+ // Check if the GraphQL type exists before registering
49
+ // This allows the plugin to work even when optional dependencies are missing
50
+ // (e.g., GeoJSON requires PostGIS plugin)
51
+ const gqlType = build.getTypeByName(type);
52
+ if (gqlType) {
53
+ build.pgRegisterGqlTypeByTypeId(pgType.id, () => gqlType);
54
+ // Store mapping for field resolver
55
+ typeMappingsByTypeId.set(pgType.id, { gqlType, pgType });
56
+ }
57
+ // If the type doesn't exist, silently skip this mapping
58
+ }
59
+ }
60
+ return build;
61
+ });
62
+ // Add field resolver to convert composite types to scalar values
63
+ builder.hook('GraphQLObjectType:fields:field', (field, build, context) => {
64
+ const { scope: { pgFieldIntrospection: attr, fieldName } } = context;
65
+ // Only process PostgreSQL table fields
66
+ if (!attr || !attr.type) {
67
+ return field;
68
+ }
69
+ // Check if this field's type is in our mappings
70
+ const mapping = typeMappingsByTypeId.get(attr.type.id);
71
+ if (!mapping) {
72
+ return field;
73
+ }
74
+ // Only process composite types (type === 'c')
75
+ // @ts-ignore
76
+ if (attr.type.type !== 'c') {
77
+ return field;
78
+ }
79
+ // Get the composite type's attributes
80
+ // @ts-ignore
81
+ const compositeType = attr.type.class;
82
+ if (!compositeType || !compositeType.attributes) {
83
+ return field;
84
+ }
85
+ // Extract the old resolver
86
+ const { resolve: oldResolve, ...rest } = field;
87
+ const defaultResolver = (obj) => {
88
+ const value = oldResolve ? oldResolve(obj) : (fieldName ? obj[fieldName] : undefined);
89
+ if (value == null) {
90
+ return null;
91
+ }
92
+ // If value is already a scalar, return it
93
+ if (typeof value !== 'object' || Array.isArray(value)) {
94
+ return value;
95
+ }
96
+ // For composite types mapped to scalars, extract the first field's value
97
+ // This handles types like email(value text) -> extract value
98
+ const attributes = compositeType.attributes;
99
+ if (attributes && attributes.length > 0) {
100
+ // Try to extract the first attribute's value
101
+ // PostgreSQL composite types are returned as objects with attribute names as keys
102
+ const firstAttr = attributes[0];
103
+ // @ts-ignore
104
+ const attrFieldName = firstAttr.name;
105
+ // Try the PostgreSQL attribute name directly
106
+ if (value[attrFieldName] !== undefined) {
107
+ return value[attrFieldName];
108
+ }
109
+ // Try camelCase version (PostGraphile might convert field names)
110
+ const camelCaseName = attrFieldName.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
111
+ if (value[camelCaseName] !== undefined) {
112
+ return value[camelCaseName];
113
+ }
114
+ // Fallback: return the first property value
115
+ const firstKey = Object.keys(value)[0];
116
+ if (firstKey) {
117
+ return value[firstKey];
118
+ }
119
+ }
120
+ // If we can't extract, return the value as-is (might be JSON)
121
+ return value;
122
+ };
123
+ return {
124
+ ...rest,
125
+ resolve: defaultResolver
126
+ };
127
+ });
128
+ };
129
+ export default CustomPgTypeMappingsPlugin;
package/index.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { Plugin } from 'graphile-build';
2
+ export interface TypeMapping {
3
+ name: string;
4
+ namespaceName: string;
5
+ type: string;
6
+ }
7
+ export interface CustomPgTypeMappingsPluginOptions {
8
+ /**
9
+ * Additional type mappings to add or override default mappings.
10
+ * Mappings are processed in order, so later mappings override earlier ones.
11
+ */
12
+ customTypeMappings?: TypeMapping[];
13
+ }
14
+ declare const CustomPgTypeMappingsPlugin: Plugin;
15
+ export default CustomPgTypeMappingsPlugin;
package/index.js ADDED
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const DEFAULT_MAPPINGS = [
4
+ { name: 'email', namespaceName: 'public', type: 'String' },
5
+ { name: 'hostname', namespaceName: 'public', type: 'String' },
6
+ { name: 'multiple_select', namespaceName: 'public', type: 'JSON' },
7
+ { name: 'single_select', namespaceName: 'public', type: 'JSON' },
8
+ { name: 'origin', namespaceName: 'public', type: 'String' },
9
+ { name: 'url', namespaceName: 'public', type: 'String' },
10
+ ];
11
+ const CustomPgTypeMappingsPlugin = (builder, options) => {
12
+ const opts = (options || {});
13
+ const customMappings = opts.customTypeMappings || [];
14
+ // Merge default mappings with custom mappings
15
+ // Custom mappings override defaults if they have the same name and namespaceName
16
+ const allMappings = [];
17
+ const seen = new Set();
18
+ // First add defaults
19
+ for (const mapping of DEFAULT_MAPPINGS) {
20
+ const key = `${mapping.namespaceName}.${mapping.name}`;
21
+ if (!seen.has(key)) {
22
+ allMappings.push(mapping);
23
+ seen.add(key);
24
+ }
25
+ }
26
+ // Then add/override with custom mappings
27
+ for (const mapping of customMappings) {
28
+ const key = `${mapping.namespaceName}.${mapping.name}`;
29
+ if (seen.has(key)) {
30
+ // Override existing mapping
31
+ const index = allMappings.findIndex(m => m.name === mapping.name && m.namespaceName === mapping.namespaceName);
32
+ if (index !== -1) {
33
+ allMappings[index] = mapping;
34
+ }
35
+ }
36
+ else {
37
+ // Add new mapping
38
+ allMappings.push(mapping);
39
+ seen.add(key);
40
+ }
41
+ }
42
+ // Store mappings for use in field resolver
43
+ const typeMappingsByTypeId = new Map();
44
+ builder.hook('build', (build, _context) => {
45
+ for (const { name, namespaceName, type } of allMappings) {
46
+ const pgType = build.pgIntrospectionResultsByKind.type.find(
47
+ // @ts-ignore
48
+ t => t.name === name && t.namespaceName === namespaceName);
49
+ if (pgType) {
50
+ // Check if the GraphQL type exists before registering
51
+ // This allows the plugin to work even when optional dependencies are missing
52
+ // (e.g., GeoJSON requires PostGIS plugin)
53
+ const gqlType = build.getTypeByName(type);
54
+ if (gqlType) {
55
+ build.pgRegisterGqlTypeByTypeId(pgType.id, () => gqlType);
56
+ // Store mapping for field resolver
57
+ typeMappingsByTypeId.set(pgType.id, { gqlType, pgType });
58
+ }
59
+ // If the type doesn't exist, silently skip this mapping
60
+ }
61
+ }
62
+ return build;
63
+ });
64
+ // Add field resolver to convert composite types to scalar values
65
+ builder.hook('GraphQLObjectType:fields:field', (field, build, context) => {
66
+ const { scope: { pgFieldIntrospection: attr, fieldName } } = context;
67
+ // Only process PostgreSQL table fields
68
+ if (!attr || !attr.type) {
69
+ return field;
70
+ }
71
+ // Check if this field's type is in our mappings
72
+ const mapping = typeMappingsByTypeId.get(attr.type.id);
73
+ if (!mapping) {
74
+ return field;
75
+ }
76
+ // Only process composite types (type === 'c')
77
+ // @ts-ignore
78
+ if (attr.type.type !== 'c') {
79
+ return field;
80
+ }
81
+ // Get the composite type's attributes
82
+ // @ts-ignore
83
+ const compositeType = attr.type.class;
84
+ if (!compositeType || !compositeType.attributes) {
85
+ return field;
86
+ }
87
+ // Extract the old resolver
88
+ const { resolve: oldResolve, ...rest } = field;
89
+ const defaultResolver = (obj) => {
90
+ const value = oldResolve ? oldResolve(obj) : (fieldName ? obj[fieldName] : undefined);
91
+ if (value == null) {
92
+ return null;
93
+ }
94
+ // If value is already a scalar, return it
95
+ if (typeof value !== 'object' || Array.isArray(value)) {
96
+ return value;
97
+ }
98
+ // For composite types mapped to scalars, extract the first field's value
99
+ // This handles types like email(value text) -> extract value
100
+ const attributes = compositeType.attributes;
101
+ if (attributes && attributes.length > 0) {
102
+ // Try to extract the first attribute's value
103
+ // PostgreSQL composite types are returned as objects with attribute names as keys
104
+ const firstAttr = attributes[0];
105
+ // @ts-ignore
106
+ const attrFieldName = firstAttr.name;
107
+ // Try the PostgreSQL attribute name directly
108
+ if (value[attrFieldName] !== undefined) {
109
+ return value[attrFieldName];
110
+ }
111
+ // Try camelCase version (PostGraphile might convert field names)
112
+ const camelCaseName = attrFieldName.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
113
+ if (value[camelCaseName] !== undefined) {
114
+ return value[camelCaseName];
115
+ }
116
+ // Fallback: return the first property value
117
+ const firstKey = Object.keys(value)[0];
118
+ if (firstKey) {
119
+ return value[firstKey];
120
+ }
121
+ }
122
+ // If we can't extract, return the value as-is (might be JSON)
123
+ return value;
124
+ };
125
+ return {
126
+ ...rest,
127
+ resolve: defaultResolver
128
+ };
129
+ });
130
+ };
131
+ exports.default = CustomPgTypeMappingsPlugin;
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "graphile-pg-type-mappings",
3
+ "version": "0.2.0",
4
+ "description": "Custom PostgreSQL type mappings plugin for Graphile/PostGraphile",
5
+ "author": "Dan Lynch <pyramation@gmail.com>",
6
+ "homepage": "https://github.com/launchql/launchql",
7
+ "license": "MIT",
8
+ "main": "index.js",
9
+ "module": "esm/index.js",
10
+ "types": "index.d.ts",
11
+ "scripts": {
12
+ "clean": "makage clean",
13
+ "copy": "makage assets",
14
+ "prepack": "npm run build",
15
+ "build": "makage build",
16
+ "build:dev": "makage build --dev",
17
+ "lint": "eslint . --fix",
18
+ "test": "jest",
19
+ "test:watch": "jest --watch"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "directory": "dist"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "https://github.com/launchql/launchql"
28
+ },
29
+ "keywords": [
30
+ "graphile",
31
+ "postgraphile",
32
+ "postgres",
33
+ "graphql",
34
+ "plugin",
35
+ "type-mappings",
36
+ "launchql"
37
+ ],
38
+ "bugs": {
39
+ "url": "https://github.com/launchql/launchql/issues"
40
+ },
41
+ "devDependencies": {
42
+ "graphile-postgis": "^0.1.2",
43
+ "graphile-test": "^2.8.10",
44
+ "graphql-tag": "2.12.6",
45
+ "makage": "^0.1.6",
46
+ "pgsql-test": "^2.14.13"
47
+ },
48
+ "dependencies": {
49
+ "graphile-build": "^4.14.1"
50
+ },
51
+ "gitHead": "4e1ff9771c2b07808a9830281abc24d12c689187"
52
+ }