@constructive-io/graphql-test 2.11.5

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 Constructive <developers@constructive.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,282 @@
1
+ # @constructive-io/graphql-test
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/constructive/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/@constructive-io/graphql-test">
15
+ <img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=graphql%2Ftest%2Fpackage.json"/>
16
+ </a>
17
+ </p>
18
+
19
+ `@constructive-io/graphql-test` builds on top of [`pgsql-test`](https://www.npmjs.com/package/pgsql-test) to provide robust GraphQL testing utilities for PostGraphile-based projects **with all Constructive plugins pre-configured**.
20
+
21
+ It provides a seamless setup for isolated, seeded, role-aware Postgres databases and injects GraphQL helpers for snapshot testing, role context, and mutation/query assertions. This package includes all the default plugins from `graphile-settings` (connection filters, full-text search, PostGIS, uploads, i18n, etc.) for a batteries-included testing experience.
22
+
23
+ ## ๐Ÿš€ Features
24
+
25
+ * ๐Ÿ” **Per-test rollback** via savepoints for isolation
26
+ * ๐Ÿ” **RLS-aware context injection** (`setContext`)
27
+ * ๐Ÿงช **GraphQL integration testing** with `query()` and snapshot support
28
+ * ๐Ÿ“ฆ **Seed support** for `.sql`, JSON, CSV, Constructive, or Sqitch
29
+ * ๐Ÿ“Š **Introspection query snapshotting**
30
+ * ๐Ÿ”ง **Raw SQL fallback** via `pg.client.query`
31
+
32
+ ## ๐Ÿ“ฆ Install
33
+
34
+ ```bash
35
+ npm install @constructive-io/graphql-test
36
+ ```
37
+
38
+ ## โœจ Quick Start
39
+
40
+ ```ts
41
+ import { getConnections, seed } from '@constructive-io/graphql-test';
42
+
43
+ let db, query, teardown;
44
+
45
+ beforeAll(async () => {
46
+ ({ db, query, teardown } = await getConnections({
47
+ schemas: ['app_public'],
48
+ authRole: 'authenticated'
49
+ }, [
50
+ seed.sqlfile(['../sql/test.sql', '../sql/grants.sql'])
51
+ ]));
52
+ });
53
+
54
+ beforeEach(() => db.beforeEach());
55
+ afterEach(() => db.afterEach());
56
+ afterAll(() => teardown());
57
+
58
+ it('runs a GraphQL mutation', async () => {
59
+ const res = await query(`mutation { ... }`, { input: { ... } });
60
+ expect(res.data.createUser.username).toBe('alice');
61
+ });
62
+ ```
63
+
64
+ ## ๐Ÿ“˜ API
65
+
66
+ ### `getConnections(options, seeders)`
67
+
68
+ Returns an object with:
69
+
70
+ * `query(gqlString, variables?)` โ€“ A GraphQL executor function with positional arguments
71
+ * `db`, `pg` โ€“ `PgTestClient` instances
72
+ * `teardown()` โ€“ Clean up temp DBs
73
+
74
+ **Basic Usage:**
75
+ ```ts
76
+ const result = await query(`mutation { ... }`, { input: { ... } });
77
+ expect(result.data.createUser.username).toBe('alice');
78
+ ```
79
+
80
+ ### `PgTestClient`
81
+
82
+ Supports:
83
+
84
+ * `query`, `any`, `one`, etc. (via `pg-promise`-like helpers)
85
+ * `beforeEach()` / `afterEach()` โ€“ for savepoint transaction handling
86
+ * `setContext({...})` โ€“ sets Postgres config (e.g., `role`, `myapp.user_id`)
87
+
88
+ **See full `PgTestClient` API docs**: [pgsql-test โ†’ PgTestClient API Overview](https://www.npmjs.com/package/pgsql-test#pgtestclient-api-overview)
89
+
90
+ ## ๐Ÿงช Example Tests
91
+
92
+ ### GraphQL mutation + snapshot
93
+
94
+ ```ts
95
+ const res = await query(`mutation { ... }`, { input: { ... } });
96
+ expect(snapshot(res.data)).toMatchSnapshot();
97
+ ```
98
+
99
+ ### RLS testing with role switch
100
+
101
+ ```ts
102
+ db.setContext({ role: 'anonymous' });
103
+ const res = await query(`query { ... }`);
104
+ expect(res.errors[0].message).toMatch(/permission denied/);
105
+ ```
106
+
107
+ ### Typed queries for better safety
108
+
109
+ ```ts
110
+ interface CreateUserVariables {
111
+ input: {
112
+ user: {
113
+ username: string;
114
+ };
115
+ };
116
+ }
117
+
118
+ interface CreateUserResult {
119
+ createUser: {
120
+ user: {
121
+ id: number;
122
+ username: string;
123
+ };
124
+ };
125
+ }
126
+
127
+ const res = await query<CreateUserResult, CreateUserVariables>(`
128
+ mutation CreateUser($input: CreateUserInput!) {
129
+ createUser(input: $input) {
130
+ user {
131
+ id
132
+ username
133
+ }
134
+ }
135
+ }
136
+ `,
137
+ { input: { user: { username: 'alice' } } }
138
+ );
139
+
140
+ expect(res.data?.createUser.user.username).toBe('alice');
141
+ ```
142
+
143
+ ## ๐Ÿ”ง Advanced Connection Options
144
+
145
+ For specific testing needs, additional connection functions are available:
146
+
147
+ ### Error Handling Variants
148
+ - `getConnectionsUnwrapped()` โ€“ Automatically throws on GraphQL errors, returns data directly
149
+
150
+ ### Debugging Variants
151
+ - `getConnectionsWithLogging()` โ€“ Logs all queries and responses
152
+ - `getConnectionsWithTiming()` โ€“ Times query execution
153
+
154
+ ### Object-Based API
155
+ - `getConnectionsObject()` โ€“ Uses `query({ query: "...", variables: {} })` syntax
156
+ - `getConnectionsObjectUnwrapped()` โ€“ Object-based with automatic error throwing
157
+
158
+ **Unwrapped Example (cleaner assertions):**
159
+ ```ts
160
+ import { getConnectionsUnwrapped } from 'graphile-test';
161
+
162
+ const { query } = await getConnectionsUnwrapped(config);
163
+
164
+ // Throws automatically on GraphQL errors, returns data directly
165
+ const result = await query(`mutation { ... }`, { input: { ... } });
166
+ expect(result.createUser.username).toBe('alice'); // No .data needed!
167
+ ```
168
+
169
+ **Object-Based Example:**
170
+ ```ts
171
+ import { getConnectionsObject } from 'graphile-test';
172
+
173
+ const { query } = await getConnectionsObject(config);
174
+
175
+ const result = await query({
176
+ query: `mutation { ... }`,
177
+ variables: { input: { ... } }
178
+ });
179
+ expect(result.data.createUser.username).toBe('alice');
180
+ ```
181
+
182
+ ## ๐Ÿงฑ Under the Hood
183
+
184
+ `graphile-test` wraps and extends `pgsql-test` with GraphQL helpers like `query()` and introspection snapshot tools. You can drop into raw SQL testing anytime via `pg.client.query()` (superuser) or `db.client.query()` (RLS user).
185
+
186
+ ## โœ… Best Practices
187
+
188
+ * Use `db.setContext({ role, user_id })` to simulate authentication.
189
+ * Always wrap tests with `beforeEach` / `afterEach`.
190
+ * Use `snapshot()` to track GraphQL result changes.
191
+ * Use `useRoot: true` to test schema visibility without RLS.
192
+ * Start with `getConnections()` for most use cases.
193
+ * Consider `getConnectionsUnwrapped()` for cleaner test assertions.
194
+
195
+ ## Snapshot Utilities
196
+
197
+ The `@constructive-io/graphql-test/utils` module provides utilities for sanitizing query results for snapshot testing. These helpers replace dynamic values (IDs, UUIDs, dates, hashes) with stable placeholders, making snapshots deterministic.
198
+
199
+ ```ts
200
+ import { snapshot } from '@constructive-io/graphql-test/utils';
201
+
202
+ const res = await query(`query { allUsers { nodes { id name createdAt } } }`);
203
+ expect(snapshot(res.data)).toMatchSnapshot();
204
+ ```
205
+
206
+ See [`pgsql-test` Snapshot Utilities](https://www.npmjs.com/package/pgsql-test#snapshot-utilities) for the full API reference.
207
+
208
+ ---
209
+
210
+ ## Education and Tutorials
211
+
212
+ 1. ๐Ÿš€ [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
213
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
214
+
215
+ 2. ๐Ÿ“ฆ [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
216
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
217
+
218
+ 3. โœ๏ธ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
219
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
220
+
221
+ 4. ๐Ÿงช [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
222
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
223
+
224
+ 5. โšก [Supabase Testing](https://constructive.io/learn/supabase)
225
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
226
+
227
+ 6. ๐Ÿ’ง [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
228
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
229
+
230
+ 7. ๐Ÿ”ง [Troubleshooting](https://constructive.io/learn/troubleshooting)
231
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
232
+
233
+ ## Related Constructive Tooling
234
+
235
+ ### ๐Ÿงช Testing
236
+
237
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **๐Ÿ“Š Isolated testing environments** with per-test transaction rollbacksโ€”ideal for integration tests, complex migrations, and RLS simulation.
238
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **๐Ÿงช Supabase-native test harness** preconfigured for the local Supabase stackโ€”per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
239
+ * [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **๐Ÿ” Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
240
+ * [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/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.
241
+
242
+ ### ๐Ÿง  Parsing & AST
243
+
244
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **๐Ÿ”„ SQL conversion engine** that interprets and converts PostgreSQL syntax.
245
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **๐ŸŒ‰ Node.js bindings** for `libpg_query`, converting SQL into parse trees.
246
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **๐Ÿ“ฆ Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
247
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **๐Ÿท๏ธ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
248
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **๐Ÿ“ Type definitions** for PostgreSQL AST nodes in TypeScript.
249
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **๐Ÿ› ๏ธ AST utilities** for constructing and transforming PostgreSQL syntax trees.
250
+ * [pg-ast](https://www.npmjs.com/package/pg-ast): **๐Ÿ” Low-level AST tools** and transformations for Postgres query structures.
251
+
252
+ ### ๐Ÿš€ API & Dev Tools
253
+
254
+ * [@constructive-io/graphql-server](https://github.com/constructive-io/constructive/tree/main/graphql/server): **โšก Express-based API server** powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
255
+ * [@constructive-io/graphql-explorer](https://github.com/constructive-io/constructive/tree/main/graphql/explorer): **๐Ÿ”Ž Visual API explorer** with GraphiQL for browsing across all databases and schemasโ€”useful for debugging, documentation, and API prototyping.
256
+
257
+ ### ๐Ÿ” Streaming & Uploads
258
+
259
+ * [etag-hash](https://github.com/constructive-io/constructive/tree/main/streaming/etag-hash): **๐Ÿท๏ธ S3-compatible ETags** created by streaming and hashing file uploads in chunks.
260
+ * [etag-stream](https://github.com/constructive-io/constructive/tree/main/streaming/etag-stream): **๐Ÿ”„ ETag computation** via Node stream transformer during upload or transfer.
261
+ * [uuid-hash](https://github.com/constructive-io/constructive/tree/main/streaming/uuid-hash): **๐Ÿ†” Deterministic UUIDs** generated from hashed content, great for deduplication and asset referencing.
262
+ * [uuid-stream](https://github.com/constructive-io/constructive/tree/main/streaming/uuid-stream): **๐ŸŒŠ Streaming UUID generation** based on piped file contentโ€”ideal for upload pipelines.
263
+ * [@constructive-io/s3-streamer](https://github.com/constructive-io/constructive/tree/main/streaming/s3-streamer): **๐Ÿ“ค Direct S3 streaming** for large files with support for metadata injection and content validation.
264
+ * [@constructive-io/upload-names](https://github.com/constructive-io/constructive/tree/main/streaming/upload-names): **๐Ÿ“‚ Collision-resistant filenames** utility for structured and unique file names for uploads.
265
+
266
+ ### ๐Ÿงฐ CLI & Codegen
267
+
268
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **๐Ÿ–ฅ๏ธ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
269
+ * [@constructive-io/cli](https://github.com/constructive-io/constructive/tree/main/packages/cli): **๐Ÿ–ฅ๏ธ Command-line toolkit** for managing Constructive projectsโ€”supports database scaffolding, migrations, seeding, code generation, and automation.
270
+ * [@constructive-io/graphql-codegen](https://github.com/constructive-io/constructive/tree/main/graphql/codegen): **โœจ GraphQL code generation** (types, operations, SDK) from schema/endpoint introspection.
271
+ * [@constructive-io/query-builder](https://github.com/constructive-io/constructive/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.
272
+ * [@constructive-io/graphql-query](https://github.com/constructive-io/constructive/tree/main/graphql/query): **๐Ÿงฉ Fluent GraphQL builder** for PostGraphile schemas. โšก Schema-aware via introspection, ๐Ÿงฉ composable and ergonomic for building deeply nested queries.
273
+
274
+ ## Credits
275
+
276
+ **๐Ÿ›  Built by the [Constructive](https://constructive.io) team โ€” creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
277
+
278
+ ## Disclaimer
279
+
280
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
281
+
282
+ 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.
@@ -0,0 +1,162 @@
1
+ import { getConnections as getPgConnections } from 'pgsql-test';
2
+ import { GraphQLTest } from './graphile-test';
3
+ // Core unwrapping utility
4
+ const unwrap = (res) => {
5
+ if (res.errors?.length) {
6
+ throw new Error(JSON.stringify(res.errors, null, 2));
7
+ }
8
+ if (!res.data) {
9
+ throw new Error('No data returned from GraphQL query');
10
+ }
11
+ return res.data;
12
+ };
13
+ // Base connection setup - shared across all variants
14
+ const createConnectionsBase = async (input, seedAdapters) => {
15
+ const conn = await getPgConnections(input, seedAdapters);
16
+ const { pg, db, teardown: dbTeardown } = conn;
17
+ const gqlContext = GraphQLTest(input, conn);
18
+ await gqlContext.setup();
19
+ const teardown = async () => {
20
+ await gqlContext.teardown();
21
+ await dbTeardown();
22
+ };
23
+ const baseQuery = (opts) => gqlContext.query(opts);
24
+ const baseQueryPositional = (query, variables, commit, reqOptions) => gqlContext.query({ query, variables, commit, reqOptions });
25
+ return {
26
+ pg,
27
+ db,
28
+ teardown,
29
+ baseQuery,
30
+ baseQueryPositional
31
+ };
32
+ };
33
+ // ============================================================================
34
+ // REGULAR QUERY VERSIONS
35
+ // ============================================================================
36
+ /**
37
+ * Creates connections with raw GraphQL responses
38
+ */
39
+ export const getConnectionsObject = async (input, seedAdapters) => {
40
+ const { pg, db, teardown, baseQuery } = await createConnectionsBase(input, seedAdapters);
41
+ return {
42
+ pg,
43
+ db,
44
+ teardown,
45
+ query: baseQuery
46
+ };
47
+ };
48
+ /**
49
+ * Creates connections with unwrapped GraphQL responses (throws on errors)
50
+ */
51
+ export const getConnectionsObjectUnwrapped = async (input, seedAdapters) => {
52
+ const { pg, db, teardown, baseQuery } = await createConnectionsBase(input, seedAdapters);
53
+ const query = async (opts) => unwrap(await baseQuery(opts));
54
+ return {
55
+ pg,
56
+ db,
57
+ teardown,
58
+ query
59
+ };
60
+ };
61
+ /**
62
+ * Creates connections with logging for GraphQL queries
63
+ */
64
+ export const getConnectionsObjectWithLogging = async (input, seedAdapters) => {
65
+ const { pg, db, teardown, baseQuery } = await createConnectionsBase(input, seedAdapters);
66
+ const query = async (opts) => {
67
+ console.log('Executing GraphQL query:', opts.query);
68
+ const result = await baseQuery(opts);
69
+ console.log('GraphQL result:', result);
70
+ return result;
71
+ };
72
+ return {
73
+ pg,
74
+ db,
75
+ teardown,
76
+ query
77
+ };
78
+ };
79
+ /**
80
+ * Creates connections with timing for GraphQL queries
81
+ */
82
+ export const getConnectionsObjectWithTiming = async (input, seedAdapters) => {
83
+ const { pg, db, teardown, baseQuery } = await createConnectionsBase(input, seedAdapters);
84
+ const query = async (opts) => {
85
+ const start = Date.now();
86
+ const result = await baseQuery(opts);
87
+ const duration = Date.now() - start;
88
+ console.log(`GraphQL query took ${duration}ms`);
89
+ return result;
90
+ };
91
+ return {
92
+ pg,
93
+ db,
94
+ teardown,
95
+ query
96
+ };
97
+ };
98
+ // ============================================================================
99
+ // POSITIONAL QUERY VERSIONS
100
+ // ============================================================================
101
+ /**
102
+ * Creates connections with raw GraphQL responses (positional API)
103
+ */
104
+ export const getConnections = async (input, seedAdapters) => {
105
+ const { pg, db, teardown, baseQueryPositional } = await createConnectionsBase(input, seedAdapters);
106
+ return {
107
+ pg,
108
+ db,
109
+ teardown,
110
+ query: baseQueryPositional
111
+ };
112
+ };
113
+ /**
114
+ * Creates connections with unwrapped GraphQL responses (positional API, throws on errors)
115
+ */
116
+ export const getConnectionsUnwrapped = async (input, seedAdapters) => {
117
+ const { pg, db, teardown, baseQueryPositional } = await createConnectionsBase(input, seedAdapters);
118
+ const query = async (query, variables, commit, reqOptions) => unwrap(await baseQueryPositional(query, variables, commit, reqOptions));
119
+ return {
120
+ pg,
121
+ db,
122
+ teardown,
123
+ query
124
+ };
125
+ };
126
+ /**
127
+ * Creates connections with logging for GraphQL queries (positional API)
128
+ */
129
+ export const getConnectionsWithLogging = async (input, seedAdapters) => {
130
+ const { pg, db, teardown, baseQueryPositional } = await createConnectionsBase(input, seedAdapters);
131
+ const query = async (query, variables, commit, reqOptions) => {
132
+ console.log('Executing positional GraphQL query:', query);
133
+ const result = await baseQueryPositional(query, variables, commit, reqOptions);
134
+ console.log('GraphQL result:', result);
135
+ return result;
136
+ };
137
+ return {
138
+ pg,
139
+ db,
140
+ teardown,
141
+ query
142
+ };
143
+ };
144
+ /**
145
+ * Creates connections with timing for GraphQL queries (positional API)
146
+ */
147
+ export const getConnectionsWithTiming = async (input, seedAdapters) => {
148
+ const { pg, db, teardown, baseQueryPositional } = await createConnectionsBase(input, seedAdapters);
149
+ const query = async (query, variables, commit, reqOptions) => {
150
+ const start = Date.now();
151
+ const result = await baseQueryPositional(query, variables, commit, reqOptions);
152
+ const duration = Date.now() - start;
153
+ console.log(`Positional GraphQL query took ${duration}ms`);
154
+ return result;
155
+ };
156
+ return {
157
+ pg,
158
+ db,
159
+ teardown,
160
+ query
161
+ };
162
+ };
@@ -0,0 +1,51 @@
1
+ import { getGraphileSettings } from 'graphile-settings';
2
+ import { createPostGraphileSchema } from 'postgraphile';
3
+ import { runGraphQLInContext } from 'graphile-test/context';
4
+ export const GraphQLTest = (input, conn) => {
5
+ const { schemas, authRole, graphile } = input;
6
+ let schema;
7
+ let options;
8
+ const pgPool = conn.manager.getPool(conn.pg.config);
9
+ const setup = async () => {
10
+ // Get base settings from graphile-settings
11
+ const baseOptions = getGraphileSettings({ graphile: { schema: schemas } });
12
+ // Merge custom graphile options
13
+ options = {
14
+ ...baseOptions,
15
+ // Merge appendPlugins if provided
16
+ ...(graphile?.appendPlugins && {
17
+ appendPlugins: [
18
+ ...(baseOptions.appendPlugins || []),
19
+ ...graphile.appendPlugins
20
+ ]
21
+ }),
22
+ // Merge graphileBuildOptions if provided
23
+ ...(graphile?.graphileBuildOptions && {
24
+ graphileBuildOptions: {
25
+ ...baseOptions.graphileBuildOptions,
26
+ ...graphile.graphileBuildOptions
27
+ }
28
+ }),
29
+ // Apply overrideSettings if provided
30
+ ...(graphile?.overrideSettings || {})
31
+ };
32
+ schema = await createPostGraphileSchema(pgPool, schemas, options);
33
+ };
34
+ const teardown = async () => { };
35
+ const query = async (opts) => {
36
+ return await runGraphQLInContext({
37
+ input,
38
+ schema,
39
+ options,
40
+ authRole,
41
+ pgPool,
42
+ conn,
43
+ ...opts
44
+ });
45
+ };
46
+ return {
47
+ setup,
48
+ teardown,
49
+ query
50
+ };
51
+ };
package/esm/index.js ADDED
@@ -0,0 +1,4 @@
1
+ // Override with our custom implementations that use graphile-settings
2
+ export { GraphQLTest } from './graphile-test';
3
+ export * from './get-connections';
4
+ export { seed, snapshot } from 'pgsql-test';
package/esm/utils.js ADDED
@@ -0,0 +1 @@
1
+ export * from 'pgsql-test/utils';
@@ -0,0 +1,76 @@
1
+ import type { GetConnectionOpts } from 'pgsql-test';
2
+ import type { SeedAdapter } from 'pgsql-test/seed/types';
3
+ import type { PgTestClient } from 'pgsql-test/test-client';
4
+ import type { GetConnectionsInput, GraphQLQueryFn, GraphQLQueryFnObj, GraphQLQueryUnwrappedFn, GraphQLQueryUnwrappedFnObj } from 'graphile-test';
5
+ /**
6
+ * Creates connections with raw GraphQL responses
7
+ */
8
+ export declare const getConnectionsObject: (input: GetConnectionsInput & GetConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<{
9
+ pg: PgTestClient;
10
+ db: PgTestClient;
11
+ teardown: () => Promise<void>;
12
+ query: GraphQLQueryFnObj;
13
+ }>;
14
+ /**
15
+ * Creates connections with unwrapped GraphQL responses (throws on errors)
16
+ */
17
+ export declare const getConnectionsObjectUnwrapped: (input: GetConnectionsInput & GetConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<{
18
+ pg: PgTestClient;
19
+ db: PgTestClient;
20
+ teardown: () => Promise<void>;
21
+ query: GraphQLQueryUnwrappedFnObj;
22
+ }>;
23
+ /**
24
+ * Creates connections with logging for GraphQL queries
25
+ */
26
+ export declare const getConnectionsObjectWithLogging: (input: GetConnectionsInput & GetConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<{
27
+ pg: PgTestClient;
28
+ db: PgTestClient;
29
+ teardown: () => Promise<void>;
30
+ query: GraphQLQueryFnObj;
31
+ }>;
32
+ /**
33
+ * Creates connections with timing for GraphQL queries
34
+ */
35
+ export declare const getConnectionsObjectWithTiming: (input: GetConnectionsInput & GetConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<{
36
+ pg: PgTestClient;
37
+ db: PgTestClient;
38
+ teardown: () => Promise<void>;
39
+ query: GraphQLQueryFnObj;
40
+ }>;
41
+ /**
42
+ * Creates connections with raw GraphQL responses (positional API)
43
+ */
44
+ export declare const getConnections: (input: GetConnectionsInput & GetConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<{
45
+ pg: PgTestClient;
46
+ db: PgTestClient;
47
+ teardown: () => Promise<void>;
48
+ query: GraphQLQueryFn;
49
+ }>;
50
+ /**
51
+ * Creates connections with unwrapped GraphQL responses (positional API, throws on errors)
52
+ */
53
+ export declare const getConnectionsUnwrapped: (input: GetConnectionsInput & GetConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<{
54
+ pg: PgTestClient;
55
+ db: PgTestClient;
56
+ teardown: () => Promise<void>;
57
+ query: GraphQLQueryUnwrappedFn;
58
+ }>;
59
+ /**
60
+ * Creates connections with logging for GraphQL queries (positional API)
61
+ */
62
+ export declare const getConnectionsWithLogging: (input: GetConnectionsInput & GetConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<{
63
+ pg: PgTestClient;
64
+ db: PgTestClient;
65
+ teardown: () => Promise<void>;
66
+ query: GraphQLQueryFn;
67
+ }>;
68
+ /**
69
+ * Creates connections with timing for GraphQL queries (positional API)
70
+ */
71
+ export declare const getConnectionsWithTiming: (input: GetConnectionsInput & GetConnectionOpts, seedAdapters?: SeedAdapter[]) => Promise<{
72
+ pg: PgTestClient;
73
+ db: PgTestClient;
74
+ teardown: () => Promise<void>;
75
+ query: GraphQLQueryFn;
76
+ }>;
@@ -0,0 +1,173 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getConnectionsWithTiming = exports.getConnectionsWithLogging = exports.getConnectionsUnwrapped = exports.getConnections = exports.getConnectionsObjectWithTiming = exports.getConnectionsObjectWithLogging = exports.getConnectionsObjectUnwrapped = exports.getConnectionsObject = void 0;
4
+ const pgsql_test_1 = require("pgsql-test");
5
+ const graphile_test_1 = require("./graphile-test");
6
+ // Core unwrapping utility
7
+ const unwrap = (res) => {
8
+ if (res.errors?.length) {
9
+ throw new Error(JSON.stringify(res.errors, null, 2));
10
+ }
11
+ if (!res.data) {
12
+ throw new Error('No data returned from GraphQL query');
13
+ }
14
+ return res.data;
15
+ };
16
+ // Base connection setup - shared across all variants
17
+ const createConnectionsBase = async (input, seedAdapters) => {
18
+ const conn = await (0, pgsql_test_1.getConnections)(input, seedAdapters);
19
+ const { pg, db, teardown: dbTeardown } = conn;
20
+ const gqlContext = (0, graphile_test_1.GraphQLTest)(input, conn);
21
+ await gqlContext.setup();
22
+ const teardown = async () => {
23
+ await gqlContext.teardown();
24
+ await dbTeardown();
25
+ };
26
+ const baseQuery = (opts) => gqlContext.query(opts);
27
+ const baseQueryPositional = (query, variables, commit, reqOptions) => gqlContext.query({ query, variables, commit, reqOptions });
28
+ return {
29
+ pg,
30
+ db,
31
+ teardown,
32
+ baseQuery,
33
+ baseQueryPositional
34
+ };
35
+ };
36
+ // ============================================================================
37
+ // REGULAR QUERY VERSIONS
38
+ // ============================================================================
39
+ /**
40
+ * Creates connections with raw GraphQL responses
41
+ */
42
+ const getConnectionsObject = async (input, seedAdapters) => {
43
+ const { pg, db, teardown, baseQuery } = await createConnectionsBase(input, seedAdapters);
44
+ return {
45
+ pg,
46
+ db,
47
+ teardown,
48
+ query: baseQuery
49
+ };
50
+ };
51
+ exports.getConnectionsObject = getConnectionsObject;
52
+ /**
53
+ * Creates connections with unwrapped GraphQL responses (throws on errors)
54
+ */
55
+ const getConnectionsObjectUnwrapped = async (input, seedAdapters) => {
56
+ const { pg, db, teardown, baseQuery } = await createConnectionsBase(input, seedAdapters);
57
+ const query = async (opts) => unwrap(await baseQuery(opts));
58
+ return {
59
+ pg,
60
+ db,
61
+ teardown,
62
+ query
63
+ };
64
+ };
65
+ exports.getConnectionsObjectUnwrapped = getConnectionsObjectUnwrapped;
66
+ /**
67
+ * Creates connections with logging for GraphQL queries
68
+ */
69
+ const getConnectionsObjectWithLogging = async (input, seedAdapters) => {
70
+ const { pg, db, teardown, baseQuery } = await createConnectionsBase(input, seedAdapters);
71
+ const query = async (opts) => {
72
+ console.log('Executing GraphQL query:', opts.query);
73
+ const result = await baseQuery(opts);
74
+ console.log('GraphQL result:', result);
75
+ return result;
76
+ };
77
+ return {
78
+ pg,
79
+ db,
80
+ teardown,
81
+ query
82
+ };
83
+ };
84
+ exports.getConnectionsObjectWithLogging = getConnectionsObjectWithLogging;
85
+ /**
86
+ * Creates connections with timing for GraphQL queries
87
+ */
88
+ const getConnectionsObjectWithTiming = async (input, seedAdapters) => {
89
+ const { pg, db, teardown, baseQuery } = await createConnectionsBase(input, seedAdapters);
90
+ const query = async (opts) => {
91
+ const start = Date.now();
92
+ const result = await baseQuery(opts);
93
+ const duration = Date.now() - start;
94
+ console.log(`GraphQL query took ${duration}ms`);
95
+ return result;
96
+ };
97
+ return {
98
+ pg,
99
+ db,
100
+ teardown,
101
+ query
102
+ };
103
+ };
104
+ exports.getConnectionsObjectWithTiming = getConnectionsObjectWithTiming;
105
+ // ============================================================================
106
+ // POSITIONAL QUERY VERSIONS
107
+ // ============================================================================
108
+ /**
109
+ * Creates connections with raw GraphQL responses (positional API)
110
+ */
111
+ const getConnections = async (input, seedAdapters) => {
112
+ const { pg, db, teardown, baseQueryPositional } = await createConnectionsBase(input, seedAdapters);
113
+ return {
114
+ pg,
115
+ db,
116
+ teardown,
117
+ query: baseQueryPositional
118
+ };
119
+ };
120
+ exports.getConnections = getConnections;
121
+ /**
122
+ * Creates connections with unwrapped GraphQL responses (positional API, throws on errors)
123
+ */
124
+ const getConnectionsUnwrapped = async (input, seedAdapters) => {
125
+ const { pg, db, teardown, baseQueryPositional } = await createConnectionsBase(input, seedAdapters);
126
+ const query = async (query, variables, commit, reqOptions) => unwrap(await baseQueryPositional(query, variables, commit, reqOptions));
127
+ return {
128
+ pg,
129
+ db,
130
+ teardown,
131
+ query
132
+ };
133
+ };
134
+ exports.getConnectionsUnwrapped = getConnectionsUnwrapped;
135
+ /**
136
+ * Creates connections with logging for GraphQL queries (positional API)
137
+ */
138
+ const getConnectionsWithLogging = async (input, seedAdapters) => {
139
+ const { pg, db, teardown, baseQueryPositional } = await createConnectionsBase(input, seedAdapters);
140
+ const query = async (query, variables, commit, reqOptions) => {
141
+ console.log('Executing positional GraphQL query:', query);
142
+ const result = await baseQueryPositional(query, variables, commit, reqOptions);
143
+ console.log('GraphQL result:', result);
144
+ return result;
145
+ };
146
+ return {
147
+ pg,
148
+ db,
149
+ teardown,
150
+ query
151
+ };
152
+ };
153
+ exports.getConnectionsWithLogging = getConnectionsWithLogging;
154
+ /**
155
+ * Creates connections with timing for GraphQL queries (positional API)
156
+ */
157
+ const getConnectionsWithTiming = async (input, seedAdapters) => {
158
+ const { pg, db, teardown, baseQueryPositional } = await createConnectionsBase(input, seedAdapters);
159
+ const query = async (query, variables, commit, reqOptions) => {
160
+ const start = Date.now();
161
+ const result = await baseQueryPositional(query, variables, commit, reqOptions);
162
+ const duration = Date.now() - start;
163
+ console.log(`Positional GraphQL query took ${duration}ms`);
164
+ return result;
165
+ };
166
+ return {
167
+ pg,
168
+ db,
169
+ teardown,
170
+ query
171
+ };
172
+ };
173
+ exports.getConnectionsWithTiming = getConnectionsWithTiming;
@@ -0,0 +1,3 @@
1
+ import type { GraphQLTestContext, GetConnectionsInput } from 'graphile-test';
2
+ import type { GetConnectionOpts, GetConnectionResult } from 'pgsql-test';
3
+ export declare const GraphQLTest: (input: GetConnectionsInput & GetConnectionOpts, conn: GetConnectionResult) => GraphQLTestContext;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GraphQLTest = void 0;
4
+ const graphile_settings_1 = require("graphile-settings");
5
+ const postgraphile_1 = require("postgraphile");
6
+ const context_1 = require("graphile-test/context");
7
+ const GraphQLTest = (input, conn) => {
8
+ const { schemas, authRole, graphile } = input;
9
+ let schema;
10
+ let options;
11
+ const pgPool = conn.manager.getPool(conn.pg.config);
12
+ const setup = async () => {
13
+ // Get base settings from graphile-settings
14
+ const baseOptions = (0, graphile_settings_1.getGraphileSettings)({ graphile: { schema: schemas } });
15
+ // Merge custom graphile options
16
+ options = {
17
+ ...baseOptions,
18
+ // Merge appendPlugins if provided
19
+ ...(graphile?.appendPlugins && {
20
+ appendPlugins: [
21
+ ...(baseOptions.appendPlugins || []),
22
+ ...graphile.appendPlugins
23
+ ]
24
+ }),
25
+ // Merge graphileBuildOptions if provided
26
+ ...(graphile?.graphileBuildOptions && {
27
+ graphileBuildOptions: {
28
+ ...baseOptions.graphileBuildOptions,
29
+ ...graphile.graphileBuildOptions
30
+ }
31
+ }),
32
+ // Apply overrideSettings if provided
33
+ ...(graphile?.overrideSettings || {})
34
+ };
35
+ schema = await (0, postgraphile_1.createPostGraphileSchema)(pgPool, schemas, options);
36
+ };
37
+ const teardown = async () => { };
38
+ const query = async (opts) => {
39
+ return await (0, context_1.runGraphQLInContext)({
40
+ input,
41
+ schema,
42
+ options,
43
+ authRole,
44
+ pgPool,
45
+ conn,
46
+ ...opts
47
+ });
48
+ };
49
+ return {
50
+ setup,
51
+ teardown,
52
+ query
53
+ };
54
+ };
55
+ exports.GraphQLTest = GraphQLTest;
package/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { type GraphQLQueryOptions, type GraphQLTestContext, type GetConnectionsInput, type GraphQLResponse, type GraphQLQueryFn, type GraphQLQueryFnObj, type GraphQLQueryUnwrappedFn, type GraphQLQueryUnwrappedFnObj, } from 'graphile-test';
2
+ export { GraphQLTest } from './graphile-test';
3
+ export * from './get-connections';
4
+ export { seed, snapshot } from 'pgsql-test';
package/index.js ADDED
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.snapshot = exports.seed = exports.GraphQLTest = void 0;
18
+ // Override with our custom implementations that use graphile-settings
19
+ var graphile_test_1 = require("./graphile-test");
20
+ Object.defineProperty(exports, "GraphQLTest", { enumerable: true, get: function () { return graphile_test_1.GraphQLTest; } });
21
+ __exportStar(require("./get-connections"), exports);
22
+ var pgsql_test_1 = require("pgsql-test");
23
+ Object.defineProperty(exports, "seed", { enumerable: true, get: function () { return pgsql_test_1.seed; } });
24
+ Object.defineProperty(exports, "snapshot", { enumerable: true, get: function () { return pgsql_test_1.snapshot; } });
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@constructive-io/graphql-test",
3
+ "version": "2.11.5",
4
+ "author": "Constructive <developers@constructive.io>",
5
+ "description": "Constructive GraphQL Testing with all plugins loaded",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/constructive",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/constructive"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/constructive/issues"
21
+ },
22
+ "scripts": {
23
+ "clean": "makage clean",
24
+ "prepack": "npm run build",
25
+ "build": "makage build",
26
+ "build:dev": "makage build --dev",
27
+ "lint": "eslint . --fix",
28
+ "test": "jest --passWithNoTests",
29
+ "test:watch": "jest --watch"
30
+ },
31
+ "devDependencies": {
32
+ "@types/pg": "^8.16.0",
33
+ "graphql-tag": "2.12.6",
34
+ "makage": "^0.1.8"
35
+ },
36
+ "dependencies": {
37
+ "@constructive-io/graphql-env": "^2.8.4",
38
+ "@constructive-io/graphql-types": "^2.12.4",
39
+ "@pgpmjs/types": "^2.12.4",
40
+ "graphile-settings": "^2.9.5",
41
+ "graphile-test": "^2.11.5",
42
+ "graphql": "15.10.1",
43
+ "mock-req": "^0.2.0",
44
+ "pg": "^8.16.3",
45
+ "pgsql-test": "^2.17.2",
46
+ "postgraphile": "^4.14.1"
47
+ },
48
+ "keywords": [
49
+ "testing",
50
+ "graphql",
51
+ "graphile",
52
+ "constructive",
53
+ "test"
54
+ ],
55
+ "gitHead": "22cfe32e994e26a6490e04e28bab26d1e7e6345c"
56
+ }
package/utils.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from 'pgsql-test/utils';
package/utils.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("pgsql-test/utils"), exports);