@drizzle-graphql-suite/client 0.5.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Annexare Studio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,236 @@
1
+ # @drizzle-graphql-suite/client
2
+
3
+ Type-safe GraphQL client auto-generated from Drizzle schemas, with full TypeScript inference for queries, mutations, filters, and relations.
4
+
5
+ ## Quick Start
6
+
7
+ ### From Drizzle Schema (recommended)
8
+
9
+ Use `createDrizzleClient` to create a client that infers all types directly from your Drizzle schema module — no code generation needed.
10
+
11
+ ```ts
12
+ import { createDrizzleClient } from 'drizzle-graphql-suite/client'
13
+ import * as schema from './db/schema'
14
+
15
+ const client = createDrizzleClient({
16
+ schema,
17
+ config: {
18
+ suffixes: { list: 's' },
19
+ tables: { exclude: ['session', 'verification'] },
20
+ },
21
+ url: '/api/graphql',
22
+ headers: { Authorization: 'Bearer ...' },
23
+ })
24
+ ```
25
+
26
+ ### From Schema Descriptor
27
+
28
+ Use `createClient` with a codegen-generated schema descriptor when you want to decouple from the Drizzle schema at runtime (e.g., in a frontend bundle that shouldn't import server-side schema files).
29
+
30
+ ```ts
31
+ import { createClient } from 'drizzle-graphql-suite/client'
32
+ import { schema, type EntityDefs } from './generated/entity-defs'
33
+
34
+ const client = createClient<typeof schema, EntityDefs>({
35
+ schema,
36
+ url: '/api/graphql',
37
+ })
38
+ ```
39
+
40
+ ## EntityClient API
41
+
42
+ Access a typed entity client via `client.entity('name')`:
43
+
44
+ ```ts
45
+ const user = client.entity('user')
46
+ ```
47
+
48
+ Each entity client provides the following methods:
49
+
50
+ ### `query(params)`
51
+
52
+ Fetch a list of records with optional filtering, pagination, and ordering. Returns `T[]`.
53
+
54
+ ```ts
55
+ const users = await user.query({
56
+ select: {
57
+ id: true,
58
+ name: true,
59
+ email: true,
60
+ posts: {
61
+ id: true,
62
+ title: true,
63
+ comments: { id: true, body: true },
64
+ },
65
+ },
66
+ where: { email: { ilike: '%@example.com' } },
67
+ orderBy: { name: { direction: 'asc', priority: 1 } },
68
+ limit: 20,
69
+ offset: 0,
70
+ })
71
+ ```
72
+
73
+ ### `querySingle(params)`
74
+
75
+ Fetch a single record. Returns `T | null`.
76
+
77
+ ```ts
78
+ const found = await user.querySingle({
79
+ select: { id: true, name: true, email: true },
80
+ where: { id: { eq: 'some-uuid' } },
81
+ })
82
+ ```
83
+
84
+ ### `count(params?)`
85
+
86
+ Count matching records. Returns `number`.
87
+
88
+ ```ts
89
+ const total = await user.count({
90
+ where: { role: { eq: 'admin' } },
91
+ })
92
+ ```
93
+
94
+ ### `insert(params)`
95
+
96
+ Insert multiple records. Returns `T[]` of inserted rows.
97
+
98
+ ```ts
99
+ const created = await user.insert({
100
+ values: [
101
+ { name: 'Alice', email: 'alice@example.com' },
102
+ { name: 'Bob', email: 'bob@example.com' },
103
+ ],
104
+ returning: { id: true, name: true },
105
+ })
106
+ ```
107
+
108
+ ### `insertSingle(params)`
109
+
110
+ Insert a single record. Returns `T | null`.
111
+
112
+ ```ts
113
+ const created = await user.insertSingle({
114
+ values: { name: 'Alice', email: 'alice@example.com' },
115
+ returning: { id: true, name: true },
116
+ })
117
+ ```
118
+
119
+ ### `update(params)`
120
+
121
+ Update records matching a filter. Returns `T[]` of updated rows.
122
+
123
+ ```ts
124
+ const updated = await user.update({
125
+ set: { role: 'admin' },
126
+ where: { id: { eq: 'some-uuid' } },
127
+ returning: { id: true, role: true },
128
+ })
129
+ ```
130
+
131
+ ### `delete(params)`
132
+
133
+ Delete records matching a filter. Returns `T[]` of deleted rows.
134
+
135
+ ```ts
136
+ const deleted = await user.delete({
137
+ where: { deletedAt: { isNotNull: true } },
138
+ returning: { id: true },
139
+ })
140
+ ```
141
+
142
+ ## Schema Descriptor
143
+
144
+ A `SchemaDescriptor` is a runtime object mapping entity names to their operation names, fields, and relations. It tells the client how to build GraphQL queries.
145
+
146
+ ### `buildSchemaDescriptor(schema, config?)`
147
+
148
+ Builds a `SchemaDescriptor` from a Drizzle schema module. This is called internally by `createDrizzleClient`, but can be used directly if you need the descriptor.
149
+
150
+ ```ts
151
+ import { buildSchemaDescriptor } from 'drizzle-graphql-suite/client'
152
+ import * as schema from './db/schema'
153
+
154
+ const descriptor = buildSchemaDescriptor(schema, {
155
+ suffixes: { list: 's' },
156
+ tables: { exclude: ['session'] },
157
+ pruneRelations: { 'user.sessions': false },
158
+ })
159
+ ```
160
+
161
+ Config options mirror the schema package: `mutations`, `suffixes`, `tables.exclude`, and `pruneRelations`.
162
+
163
+ ## Type Inference
164
+
165
+ The client provides end-to-end type inference from Drizzle schema to query results:
166
+
167
+ ### `InferEntityDefs<TSchema, TConfig>`
168
+
169
+ Infers the complete entity type definitions from a Drizzle schema module, including fields (with Date → string wire conversion), relations, filters, insert inputs, update inputs, and orderBy types.
170
+
171
+ ```ts
172
+ import type { InferEntityDefs } from 'drizzle-graphql-suite/client'
173
+ import type * as schema from './db/schema'
174
+
175
+ type MyEntityDefs = InferEntityDefs<typeof schema, { tables: { exclude: ['session'] } }>
176
+ ```
177
+
178
+ ### `InferResult<TDefs, TEntity, TSelect>`
179
+
180
+ Infers the return type of a query from the `select` object. Only selected scalar fields and relations are included in the result type. Relations resolve to arrays or `T | null` based on their cardinality.
181
+
182
+ ### `SelectInput<TDefs, TEntity>`
183
+
184
+ Describes the valid shape of a `select` parameter — `true` for scalar fields, nested objects for relations.
185
+
186
+ ## Dynamic URL and Headers
187
+
188
+ Both `url` and `headers` support static values or functions (sync or async) that are called per-request:
189
+
190
+ ```ts
191
+ const client = createDrizzleClient({
192
+ schema,
193
+ config: {},
194
+ // Dynamic URL
195
+ url: () => `${getApiBase()}/graphql`,
196
+ // Async headers (e.g., refresh token)
197
+ headers: async () => ({
198
+ Authorization: `Bearer ${await getAccessToken()}`,
199
+ }),
200
+ })
201
+ ```
202
+
203
+ ## Error Handling
204
+
205
+ The client throws two error types:
206
+
207
+ ### `GraphQLClientError`
208
+
209
+ Thrown when the server returns GraphQL errors in the response body.
210
+
211
+ - **`errors`** — `Array<{ message, locations?, path?, extensions? }>` — individual GraphQL errors
212
+ - **`status`** — HTTP status code (usually `200`)
213
+ - **`message`** — concatenated error messages
214
+
215
+ ### `NetworkError`
216
+
217
+ Thrown when the HTTP request fails (network error or non-2xx status).
218
+
219
+ - **`status`** — HTTP status code (`0` for network failures)
220
+ - **`message`** — error description
221
+
222
+ ```ts
223
+ import { GraphQLClientError, NetworkError } from 'drizzle-graphql-suite/client'
224
+
225
+ try {
226
+ const users = await client.entity('user').query({
227
+ select: { id: true, name: true },
228
+ })
229
+ } catch (e) {
230
+ if (e instanceof GraphQLClientError) {
231
+ console.error('GraphQL errors:', e.errors)
232
+ } else if (e instanceof NetworkError) {
233
+ console.error('Network error:', e.status, e.message)
234
+ }
235
+ }
236
+ ```
package/client.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { type EntityClient } from './entity';
2
+ import type { InferEntityDefs } from './infer';
3
+ import { type ClientSchemaConfig } from './schema-builder';
4
+ import type { AnyEntityDefs, ClientConfig, SchemaDescriptor } from './types';
5
+ export declare class GraphQLClient<TSchema extends SchemaDescriptor, TDefs extends AnyEntityDefs = AnyEntityDefs> {
6
+ private url;
7
+ private schema;
8
+ private headers?;
9
+ constructor(config: ClientConfig<TSchema>);
10
+ entity<TEntityName extends string & keyof TSchema & keyof TDefs>(entityName: TEntityName): EntityClient<TDefs, TDefs[TEntityName]>;
11
+ execute(query: string, variables?: Record<string, unknown>): Promise<Record<string, unknown>>;
12
+ }
13
+ export type DrizzleClientConfig<TSchema extends Record<string, unknown>, TConfig extends ClientSchemaConfig> = {
14
+ schema: TSchema;
15
+ config: TConfig;
16
+ url: string | (() => string);
17
+ headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
18
+ };
19
+ export declare function createDrizzleClient<TSchema extends Record<string, unknown>, const TConfig extends ClientSchemaConfig>(options: DrizzleClientConfig<TSchema, TConfig>): GraphQLClient<SchemaDescriptor, InferEntityDefs<TSchema, TConfig>>;
package/entity.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import type { AnyEntityDefs, EntityDef, EntityDescriptor, InferResult, SchemaDescriptor } from './types';
2
+ export type EntityClient<TDefs extends AnyEntityDefs, TEntity extends EntityDef> = {
3
+ query<S extends Record<string, unknown>>(params: {
4
+ select: S;
5
+ where?: TEntity extends {
6
+ filters: infer F;
7
+ } ? F : never;
8
+ limit?: number;
9
+ offset?: number;
10
+ orderBy?: TEntity extends {
11
+ orderBy: infer O;
12
+ } ? O : never;
13
+ }): Promise<InferResult<TDefs, TEntity, S>[]>;
14
+ querySingle<S extends Record<string, unknown>>(params: {
15
+ select: S;
16
+ where?: TEntity extends {
17
+ filters: infer F;
18
+ } ? F : never;
19
+ offset?: number;
20
+ orderBy?: TEntity extends {
21
+ orderBy: infer O;
22
+ } ? O : never;
23
+ }): Promise<InferResult<TDefs, TEntity, S> | null>;
24
+ count(params?: {
25
+ where?: TEntity extends {
26
+ filters: infer F;
27
+ } ? F : never;
28
+ }): Promise<number>;
29
+ insert<S extends Record<string, unknown>>(params: {
30
+ values: TEntity extends {
31
+ insertInput: infer I;
32
+ } ? I[] : never;
33
+ returning?: S;
34
+ }): Promise<InferResult<TDefs, TEntity, S>[]>;
35
+ insertSingle<S extends Record<string, unknown>>(params: {
36
+ values: TEntity extends {
37
+ insertInput: infer I;
38
+ } ? I : never;
39
+ returning?: S;
40
+ }): Promise<InferResult<TDefs, TEntity, S> | null>;
41
+ update<S extends Record<string, unknown>>(params: {
42
+ set: TEntity extends {
43
+ updateInput: infer U;
44
+ } ? U : never;
45
+ where?: TEntity extends {
46
+ filters: infer F;
47
+ } ? F : never;
48
+ returning?: S;
49
+ }): Promise<InferResult<TDefs, TEntity, S>[]>;
50
+ delete<S extends Record<string, unknown>>(params: {
51
+ where?: TEntity extends {
52
+ filters: infer F;
53
+ } ? F : never;
54
+ returning?: S;
55
+ }): Promise<InferResult<TDefs, TEntity, S>[]>;
56
+ };
57
+ export declare function createEntityClient<TDefs extends AnyEntityDefs, TEntity extends EntityDef>(entityName: string, entityDef: EntityDescriptor, schema: SchemaDescriptor, executeGraphQL: (query: string, variables: Record<string, unknown>) => Promise<Record<string, unknown>>): EntityClient<TDefs, TEntity>;
package/errors.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ export type GraphQLErrorLocation = {
2
+ line: number;
3
+ column: number;
4
+ };
5
+ export type GraphQLErrorEntry = {
6
+ message: string;
7
+ locations?: GraphQLErrorLocation[];
8
+ path?: (string | number)[];
9
+ extensions?: Record<string, unknown>;
10
+ };
11
+ export declare class GraphQLClientError extends Error {
12
+ readonly errors: GraphQLErrorEntry[];
13
+ readonly status: number;
14
+ constructor(errors: GraphQLErrorEntry[], status?: number);
15
+ }
16
+ export declare class NetworkError extends Error {
17
+ readonly status: number;
18
+ constructor(message: string, status: number);
19
+ }
package/index.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { GraphQLClient } from './client';
2
+ import type { AnyEntityDefs, ClientConfig, SchemaDescriptor } from './types';
3
+ export declare function createClient<TSchema extends SchemaDescriptor, TDefs extends AnyEntityDefs = AnyEntityDefs>(config: ClientConfig<TSchema>): GraphQLClient<TSchema, TDefs>;
4
+ export type { DrizzleClientConfig } from './client';
5
+ export { createDrizzleClient, GraphQLClient } from './client';
6
+ export type { EntityClient } from './entity';
7
+ export { GraphQLClientError, NetworkError } from './errors';
8
+ export type { InferEntityDefs } from './infer';
9
+ export type { ClientSchemaConfig } from './schema-builder';
10
+ export { buildSchemaDescriptor } from './schema-builder';
11
+ export type { AnyEntityDefs, ClientConfig, EntityDef, EntityDescriptor, InferResult, SchemaDescriptor, SelectInput, } from './types';
package/index.js ADDED
@@ -0,0 +1,439 @@
1
+ // src/query-builder.ts
2
+ var capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
3
+ function buildSelectionSet(select, schema, entityDef, indent = 4) {
4
+ const pad = " ".repeat(indent);
5
+ const lines = [];
6
+ for (const [key, value] of Object.entries(select)) {
7
+ if (value === true) {
8
+ lines.push(`${pad}${key}`);
9
+ continue;
10
+ }
11
+ if (typeof value === "object" && value !== null) {
12
+ const rel = entityDef.relations[key];
13
+ if (!rel)
14
+ continue;
15
+ const targetDef = schema[rel.entity];
16
+ if (!targetDef)
17
+ continue;
18
+ const inner = buildSelectionSet(value, schema, targetDef, indent + 2);
19
+ lines.push(`${pad}${key} {`);
20
+ lines.push(inner);
21
+ lines.push(`${pad}}`);
22
+ }
23
+ }
24
+ return lines.join(`
25
+ `);
26
+ }
27
+ function getFilterTypeName(entityName) {
28
+ return `${capitalize(entityName)}Filters`;
29
+ }
30
+ function getOrderByTypeName(entityName) {
31
+ return `${capitalize(entityName)}OrderBy`;
32
+ }
33
+ function getInsertInputTypeName(entityName) {
34
+ return `${capitalize(entityName)}InsertInput`;
35
+ }
36
+ function getUpdateInputTypeName(entityName) {
37
+ return `${capitalize(entityName)}UpdateInput`;
38
+ }
39
+ function buildListQuery(entityName, entityDef, schema, select, hasWhere, hasOrderBy, hasLimit, hasOffset) {
40
+ const opName = entityDef.queryListName;
41
+ if (!opName)
42
+ throw new Error(`Entity '${entityName}' has no list query`);
43
+ const filterType = getFilterTypeName(entityName);
44
+ const orderByType = getOrderByTypeName(entityName);
45
+ const operationName = `${capitalize(opName)}Query`;
46
+ const varDefs = [];
47
+ const argPairs = [];
48
+ if (hasWhere) {
49
+ varDefs.push(`$where: ${filterType}`);
50
+ argPairs.push("where: $where");
51
+ }
52
+ if (hasOrderBy) {
53
+ varDefs.push(`$orderBy: ${orderByType}`);
54
+ argPairs.push("orderBy: $orderBy");
55
+ }
56
+ if (hasLimit) {
57
+ varDefs.push("$limit: Int");
58
+ argPairs.push("limit: $limit");
59
+ }
60
+ if (hasOffset) {
61
+ varDefs.push("$offset: Int");
62
+ argPairs.push("offset: $offset");
63
+ }
64
+ const varDefsStr = varDefs.length ? `(${varDefs.join(", ")})` : "";
65
+ const argsStr = argPairs.length ? `(${argPairs.join(", ")})` : "";
66
+ const selection = buildSelectionSet(select, schema, entityDef);
67
+ const query = `query ${operationName}${varDefsStr} {
68
+ ${opName}${argsStr} {
69
+ ${selection}
70
+ }
71
+ }`;
72
+ return { query, variables: {}, operationName };
73
+ }
74
+ function buildSingleQuery(entityName, entityDef, schema, select, hasWhere, hasOrderBy, hasOffset) {
75
+ const opName = entityDef.queryName;
76
+ if (!opName)
77
+ throw new Error(`Entity '${entityName}' has no single query`);
78
+ const filterType = getFilterTypeName(entityName);
79
+ const orderByType = getOrderByTypeName(entityName);
80
+ const operationName = `${capitalize(opName)}SingleQuery`;
81
+ const varDefs = [];
82
+ const argPairs = [];
83
+ if (hasWhere) {
84
+ varDefs.push(`$where: ${filterType}`);
85
+ argPairs.push("where: $where");
86
+ }
87
+ if (hasOrderBy) {
88
+ varDefs.push(`$orderBy: ${orderByType}`);
89
+ argPairs.push("orderBy: $orderBy");
90
+ }
91
+ if (hasOffset) {
92
+ varDefs.push("$offset: Int");
93
+ argPairs.push("offset: $offset");
94
+ }
95
+ const varDefsStr = varDefs.length ? `(${varDefs.join(", ")})` : "";
96
+ const argsStr = argPairs.length ? `(${argPairs.join(", ")})` : "";
97
+ const selection = buildSelectionSet(select, schema, entityDef);
98
+ const query = `query ${operationName}${varDefsStr} {
99
+ ${opName}${argsStr} {
100
+ ${selection}
101
+ }
102
+ }`;
103
+ return { query, variables: {}, operationName };
104
+ }
105
+ function buildCountQuery(entityName, entityDef, hasWhere) {
106
+ const opName = entityDef.countName;
107
+ if (!opName)
108
+ throw new Error(`Entity '${entityName}' has no count query`);
109
+ const filterType = getFilterTypeName(entityName);
110
+ const operationName = `${capitalize(opName)}Query`;
111
+ const varDefs = [];
112
+ const argPairs = [];
113
+ if (hasWhere) {
114
+ varDefs.push(`$where: ${filterType}`);
115
+ argPairs.push("where: $where");
116
+ }
117
+ const varDefsStr = varDefs.length ? `(${varDefs.join(", ")})` : "";
118
+ const argsStr = argPairs.length ? `(${argPairs.join(", ")})` : "";
119
+ const query = `query ${operationName}${varDefsStr} {
120
+ ${opName}${argsStr}
121
+ }`;
122
+ return { query, variables: {}, operationName };
123
+ }
124
+ function buildInsertMutation(entityName, entityDef, schema, returning, isSingle) {
125
+ const opName = isSingle ? entityDef.insertSingleName : entityDef.insertName;
126
+ if (!opName)
127
+ throw new Error(`Entity '${entityName}' has no ${isSingle ? "insertSingle" : "insert"} mutation`);
128
+ const inputType = getInsertInputTypeName(entityName);
129
+ const operationName = `${capitalize(opName)}Mutation`;
130
+ const valuesType = isSingle ? `${inputType}!` : `[${inputType}!]!`;
131
+ const varDefs = `($values: ${valuesType})`;
132
+ const argsStr = "(values: $values)";
133
+ let selectionBlock = "";
134
+ if (returning) {
135
+ const selection = buildSelectionSet(returning, schema, entityDef);
136
+ selectionBlock = ` {
137
+ ${selection}
138
+ }`;
139
+ }
140
+ const query = `mutation ${operationName}${varDefs} {
141
+ ${opName}${argsStr}${selectionBlock}
142
+ }`;
143
+ return { query, variables: {}, operationName };
144
+ }
145
+ function buildUpdateMutation(entityName, entityDef, schema, returning, hasWhere) {
146
+ const opName = entityDef.updateName;
147
+ if (!opName)
148
+ throw new Error(`Entity '${entityName}' has no update mutation`);
149
+ const updateType = getUpdateInputTypeName(entityName);
150
+ const filterType = getFilterTypeName(entityName);
151
+ const operationName = `${capitalize(opName)}Mutation`;
152
+ const varDefs = [`$set: ${updateType}!`];
153
+ const argPairs = ["set: $set"];
154
+ if (hasWhere) {
155
+ varDefs.push(`$where: ${filterType}`);
156
+ argPairs.push("where: $where");
157
+ }
158
+ const varDefsStr = `(${varDefs.join(", ")})`;
159
+ const argsStr = `(${argPairs.join(", ")})`;
160
+ let selectionBlock = "";
161
+ if (returning) {
162
+ const selection = buildSelectionSet(returning, schema, entityDef);
163
+ selectionBlock = ` {
164
+ ${selection}
165
+ }`;
166
+ }
167
+ const query = `mutation ${operationName}${varDefsStr} {
168
+ ${opName}${argsStr}${selectionBlock}
169
+ }`;
170
+ return { query, variables: {}, operationName };
171
+ }
172
+ function buildDeleteMutation(entityName, entityDef, schema, returning, hasWhere) {
173
+ const opName = entityDef.deleteName;
174
+ if (!opName)
175
+ throw new Error(`Entity '${entityName}' has no delete mutation`);
176
+ const filterType = getFilterTypeName(entityName);
177
+ const operationName = `${capitalize(opName)}Mutation`;
178
+ const varDefs = [];
179
+ const argPairs = [];
180
+ if (hasWhere) {
181
+ varDefs.push(`$where: ${filterType}`);
182
+ argPairs.push("where: $where");
183
+ }
184
+ const varDefsStr = varDefs.length ? `(${varDefs.join(", ")})` : "";
185
+ const argsStr = argPairs.length ? `(${argPairs.join(", ")})` : "";
186
+ let selectionBlock = "";
187
+ if (returning) {
188
+ const selection = buildSelectionSet(returning, schema, entityDef);
189
+ selectionBlock = ` {
190
+ ${selection}
191
+ }`;
192
+ }
193
+ const query = `mutation ${operationName}${varDefsStr} {
194
+ ${opName}${argsStr}${selectionBlock}
195
+ }`;
196
+ return { query, variables: {}, operationName };
197
+ }
198
+
199
+ // src/entity.ts
200
+ function createEntityClient(entityName, entityDef, schema, executeGraphQL) {
201
+ return {
202
+ async query(params) {
203
+ const { select, where, limit, offset, orderBy } = params;
204
+ const built = buildListQuery(entityName, entityDef, schema, select, where != null, orderBy != null, limit != null, offset != null);
205
+ const variables = {};
206
+ if (where != null)
207
+ variables.where = where;
208
+ if (orderBy != null)
209
+ variables.orderBy = orderBy;
210
+ if (limit != null)
211
+ variables.limit = limit;
212
+ if (offset != null)
213
+ variables.offset = offset;
214
+ const data = await executeGraphQL(built.query, variables);
215
+ return data[entityDef.queryListName];
216
+ },
217
+ async querySingle(params) {
218
+ const { select, where, offset, orderBy } = params;
219
+ const built = buildSingleQuery(entityName, entityDef, schema, select, where != null, orderBy != null, offset != null);
220
+ const variables = {};
221
+ if (where != null)
222
+ variables.where = where;
223
+ if (orderBy != null)
224
+ variables.orderBy = orderBy;
225
+ if (offset != null)
226
+ variables.offset = offset;
227
+ const data = await executeGraphQL(built.query, variables);
228
+ return data[entityDef.queryName] ?? null;
229
+ },
230
+ async count(params) {
231
+ const where = params?.where;
232
+ const built = buildCountQuery(entityName, entityDef, where != null);
233
+ const variables = {};
234
+ if (where != null)
235
+ variables.where = where;
236
+ const data = await executeGraphQL(built.query, variables);
237
+ return data[entityDef.countName];
238
+ },
239
+ async insert(params) {
240
+ const { values, returning } = params;
241
+ const built = buildInsertMutation(entityName, entityDef, schema, returning, false);
242
+ const variables = { values };
243
+ const data = await executeGraphQL(built.query, variables);
244
+ return data[entityDef.insertName];
245
+ },
246
+ async insertSingle(params) {
247
+ const { values, returning } = params;
248
+ const built = buildInsertMutation(entityName, entityDef, schema, returning, true);
249
+ const variables = { values };
250
+ const data = await executeGraphQL(built.query, variables);
251
+ return data[entityDef.insertSingleName] ?? null;
252
+ },
253
+ async update(params) {
254
+ const { set, where, returning } = params;
255
+ const built = buildUpdateMutation(entityName, entityDef, schema, returning, where != null);
256
+ const variables = { set };
257
+ if (where != null)
258
+ variables.where = where;
259
+ const data = await executeGraphQL(built.query, variables);
260
+ return data[entityDef.updateName];
261
+ },
262
+ async delete(params) {
263
+ const { where, returning } = params;
264
+ const built = buildDeleteMutation(entityName, entityDef, schema, returning, where != null);
265
+ const variables = {};
266
+ if (where != null)
267
+ variables.where = where;
268
+ const data = await executeGraphQL(built.query, variables);
269
+ return data[entityDef.deleteName];
270
+ }
271
+ };
272
+ }
273
+
274
+ // src/errors.ts
275
+ class GraphQLClientError extends Error {
276
+ errors;
277
+ status;
278
+ constructor(errors, status = 200) {
279
+ const message = errors.map((e) => e.message).join("; ");
280
+ super(message);
281
+ this.name = "GraphQLClientError";
282
+ this.errors = errors;
283
+ this.status = status;
284
+ }
285
+ }
286
+
287
+ class NetworkError extends Error {
288
+ status;
289
+ constructor(message, status) {
290
+ super(message);
291
+ this.name = "NetworkError";
292
+ this.status = status;
293
+ }
294
+ }
295
+
296
+ // src/schema-builder.ts
297
+ import { getTableColumns, getTableName, is, Many, One, Relations, Table } from "drizzle-orm";
298
+ var capitalize2 = (s) => s.charAt(0).toUpperCase() + s.slice(1);
299
+ function buildSchemaDescriptor(schema, config = {}) {
300
+ const excludeSet = new Set(config.tables?.exclude ?? []);
301
+ const listSuffix = config.suffixes?.list ?? "s";
302
+ const tableMap = new Map;
303
+ const dbNameToKey = new Map;
304
+ for (const [key, value] of Object.entries(schema)) {
305
+ if (is(value, Table)) {
306
+ if (excludeSet.has(key))
307
+ continue;
308
+ const dbName = getTableName(value);
309
+ const cols = Object.keys(getTableColumns(value));
310
+ tableMap.set(key, { table: value, dbName, columns: cols });
311
+ dbNameToKey.set(dbName, key);
312
+ }
313
+ }
314
+ const relationsMap = new Map;
315
+ for (const value of Object.values(schema)) {
316
+ if (!is(value, Relations))
317
+ continue;
318
+ const sourceDbName = getTableName(value.table);
319
+ const sourceKey = dbNameToKey.get(sourceDbName);
320
+ if (!sourceKey || !tableMap.has(sourceKey))
321
+ continue;
322
+ const helpers = {
323
+ one: (referencedTable, cfg) => {
324
+ return new One(value.table, referencedTable, cfg, false);
325
+ },
326
+ many: (referencedTable, cfg) => {
327
+ return new Many(value.table, referencedTable, cfg);
328
+ }
329
+ };
330
+ const relConfig = value.config(helpers);
331
+ const rels = {};
332
+ for (const [relName, relValue] of Object.entries(relConfig)) {
333
+ const rel = relValue;
334
+ const targetDbName = rel.referencedTableName;
335
+ if (!targetDbName)
336
+ continue;
337
+ const targetKey = dbNameToKey.get(targetDbName);
338
+ if (!targetKey)
339
+ continue;
340
+ const type = is(rel, One) ? "one" : "many";
341
+ rels[relName] = { entity: targetKey, type };
342
+ }
343
+ relationsMap.set(sourceKey, rels);
344
+ }
345
+ const pruneRelations = config.pruneRelations ?? {};
346
+ for (const [sourceKey, rels] of relationsMap) {
347
+ for (const relName of Object.keys(rels)) {
348
+ const pruneKey = `${sourceKey}.${relName}`;
349
+ const pruneValue = pruneRelations[pruneKey];
350
+ if (pruneValue === false) {
351
+ delete rels[relName];
352
+ }
353
+ }
354
+ }
355
+ const descriptor = {};
356
+ for (const [key, { columns }] of tableMap) {
357
+ const rels = relationsMap.get(key) ?? {};
358
+ descriptor[key] = {
359
+ queryName: key,
360
+ queryListName: `${key}${listSuffix}`,
361
+ countName: `${key}Count`,
362
+ insertName: `insertInto${capitalize2(key)}`,
363
+ insertSingleName: `insertInto${capitalize2(key)}Single`,
364
+ updateName: `update${capitalize2(key)}`,
365
+ deleteName: `deleteFrom${capitalize2(key)}`,
366
+ fields: columns,
367
+ relations: rels
368
+ };
369
+ }
370
+ return descriptor;
371
+ }
372
+
373
+ // src/client.ts
374
+ class GraphQLClient {
375
+ url;
376
+ schema;
377
+ headers;
378
+ constructor(config) {
379
+ this.url = config.url;
380
+ this.schema = config.schema;
381
+ this.headers = config.headers;
382
+ }
383
+ entity(entityName) {
384
+ const entityDef = this.schema[entityName];
385
+ if (!entityDef) {
386
+ throw new Error(`Entity '${entityName}' not found in schema`);
387
+ }
388
+ return createEntityClient(entityName, entityDef, this.schema, (query, variables) => this.execute(query, variables));
389
+ }
390
+ async execute(query, variables = {}) {
391
+ const url = typeof this.url === "function" ? this.url() : this.url;
392
+ const headers = {
393
+ "Content-Type": "application/json",
394
+ ...typeof this.headers === "function" ? await this.headers() : this.headers ?? {}
395
+ };
396
+ let response;
397
+ try {
398
+ response = await fetch(url, {
399
+ method: "POST",
400
+ headers,
401
+ body: JSON.stringify({ query, variables })
402
+ });
403
+ } catch (e) {
404
+ throw new NetworkError(e instanceof Error ? e.message : "Network request failed", 0);
405
+ }
406
+ if (!response.ok) {
407
+ throw new NetworkError(`HTTP ${response.status}: ${response.statusText}`, response.status);
408
+ }
409
+ const json = await response.json();
410
+ if (json.errors?.length) {
411
+ throw new GraphQLClientError(json.errors, response.status);
412
+ }
413
+ if (!json.data) {
414
+ throw new GraphQLClientError([{ message: "No data in response" }], response.status);
415
+ }
416
+ return json.data;
417
+ }
418
+ }
419
+ function createDrizzleClient(options) {
420
+ const schema = buildSchemaDescriptor(options.schema, options.config);
421
+ return new GraphQLClient({
422
+ url: options.url,
423
+ schema,
424
+ headers: options.headers
425
+ });
426
+ }
427
+
428
+ // src/index.ts
429
+ function createClient(config) {
430
+ return new GraphQLClient(config);
431
+ }
432
+ export {
433
+ createDrizzleClient,
434
+ createClient,
435
+ buildSchemaDescriptor,
436
+ NetworkError,
437
+ GraphQLClientError,
438
+ GraphQLClient
439
+ };
package/infer.d.ts ADDED
@@ -0,0 +1,86 @@
1
+ import type { Many, One, Relations, Table } from 'drizzle-orm';
2
+ type ToWire<T> = T extends Date ? string : T;
3
+ type WireFormat<T> = {
4
+ [K in keyof T]: ToWire<T[K]>;
5
+ };
6
+ type ExtractTables<TSchema> = {
7
+ [K in keyof TSchema as TSchema[K] extends Table ? K : never]: TSchema[K];
8
+ };
9
+ type FindRelationConfig<TSchema, TTableName extends string> = {
10
+ [K in keyof TSchema]: TSchema[K] extends Relations<TTableName, infer TConfig> ? TConfig : never;
11
+ }[keyof TSchema];
12
+ type MapRelation<T> = T extends One<infer N, infer _TNullable> ? {
13
+ entity: N;
14
+ type: 'one';
15
+ } : T extends Many<infer N> ? {
16
+ entity: N;
17
+ type: 'many';
18
+ } : never;
19
+ type InferRelationDefs<TSchema, TTableName extends string> = {
20
+ [K in keyof FindRelationConfig<TSchema, TTableName>]: MapRelation<FindRelationConfig<TSchema, TTableName>[K]>;
21
+ };
22
+ type ScalarFilterOps<T> = {
23
+ eq?: T | null;
24
+ ne?: T | null;
25
+ lt?: T | null;
26
+ lte?: T | null;
27
+ gt?: T | null;
28
+ gte?: T | null;
29
+ like?: string | null;
30
+ notLike?: string | null;
31
+ ilike?: string | null;
32
+ notIlike?: string | null;
33
+ inArray?: T[] | null;
34
+ notInArray?: T[] | null;
35
+ isNull?: boolean | null;
36
+ isNotNull?: boolean | null;
37
+ };
38
+ type InferFilters<TFields> = {
39
+ [K in keyof TFields]?: ScalarFilterOps<NonNullable<TFields[K]>>;
40
+ } & {
41
+ OR?: InferFilters<TFields>[];
42
+ };
43
+ type InferInsertInput<T> = T extends Table ? WireFormat<T['$inferInsert']> : never;
44
+ type InferUpdateInput<T> = T extends Table ? {
45
+ [K in keyof T['$inferInsert']]?: ToWire<T['$inferInsert'][K]> | null;
46
+ } : never;
47
+ type InferOrderBy<T> = T extends Table ? {
48
+ [K in keyof T['$inferSelect']]?: {
49
+ direction: 'asc' | 'desc';
50
+ priority: number;
51
+ };
52
+ } : never;
53
+ type ExcludedNames<TConfig> = TConfig extends {
54
+ tables: {
55
+ exclude: readonly (infer T)[];
56
+ };
57
+ } ? T : never;
58
+ type TableDbName<T> = T extends Table<infer TConfig> ? TConfig['name'] extends string ? TConfig['name'] : string : string;
59
+ type DbNameToKey<TSchema> = {
60
+ [K in keyof ExtractTables<TSchema>]: TableDbName<ExtractTables<TSchema>[K]>;
61
+ };
62
+ type KeyForDbName<TSchema, TDbName extends string> = {
63
+ [K in keyof DbNameToKey<TSchema>]: DbNameToKey<TSchema>[K] extends TDbName ? K : never;
64
+ }[keyof DbNameToKey<TSchema>];
65
+ type ResolveRelationEntity<TSchema, TDbName extends string> = KeyForDbName<TSchema, TDbName> extends infer K ? (K extends string ? K : TDbName) : TDbName;
66
+ type ResolveRelationDefs<TSchema, TRels> = {
67
+ [K in keyof TRels]: TRels[K] extends {
68
+ entity: infer E;
69
+ type: infer T;
70
+ } ? E extends string ? {
71
+ entity: ResolveRelationEntity<TSchema, E>;
72
+ type: T;
73
+ } : TRels[K] : TRels[K];
74
+ };
75
+ type BuildEntityDef<TSchema, T> = T extends Table ? {
76
+ fields: WireFormat<T['$inferSelect']>;
77
+ relations: ResolveRelationDefs<TSchema, InferRelationDefs<TSchema, TableDbName<T>>>;
78
+ filters: InferFilters<WireFormat<T['$inferSelect']>>;
79
+ insertInput: InferInsertInput<T>;
80
+ updateInput: InferUpdateInput<T>;
81
+ orderBy: InferOrderBy<T>;
82
+ } : never;
83
+ export type InferEntityDefs<TSchema, TConfig = Record<string, never>> = {
84
+ [K in keyof ExtractTables<TSchema> as K extends ExcludedNames<TConfig> ? never : K extends string ? K : never]: BuildEntityDef<TSchema, ExtractTables<TSchema>[K]>;
85
+ };
86
+ export {};
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@drizzle-graphql-suite/client",
3
+ "version": "0.5.0",
4
+ "description": "Type-safe GraphQL client with entity-based API and full Drizzle type inference",
5
+ "license": "MIT",
6
+ "author": "https://github.com/dmythro",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/annexare/drizzle-graphql-suite.git",
10
+ "directory": "packages/client"
11
+ },
12
+ "homepage": "https://github.com/annexare/drizzle-graphql-suite/tree/main/packages/client#readme",
13
+ "keywords": [
14
+ "drizzle",
15
+ "graphql",
16
+ "client",
17
+ "type-safe",
18
+ "typescript",
19
+ "orm",
20
+ "query-builder"
21
+ ],
22
+ "type": "module",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "main": "./index.js",
27
+ "types": "./index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./index.d.ts",
31
+ "import": "./index.js"
32
+ }
33
+ },
34
+ "peerDependencies": {
35
+ "drizzle-orm": ">=0.44.0"
36
+ }
37
+ }
@@ -0,0 +1,12 @@
1
+ import type { EntityDescriptor, SchemaDescriptor } from './types';
2
+ export type BuiltQuery = {
3
+ query: string;
4
+ variables: Record<string, unknown>;
5
+ operationName: string;
6
+ };
7
+ export declare function buildListQuery(entityName: string, entityDef: EntityDescriptor, schema: SchemaDescriptor, select: Record<string, unknown>, hasWhere: boolean, hasOrderBy: boolean, hasLimit: boolean, hasOffset: boolean): BuiltQuery;
8
+ export declare function buildSingleQuery(entityName: string, entityDef: EntityDescriptor, schema: SchemaDescriptor, select: Record<string, unknown>, hasWhere: boolean, hasOrderBy: boolean, hasOffset: boolean): BuiltQuery;
9
+ export declare function buildCountQuery(entityName: string, entityDef: EntityDescriptor, hasWhere: boolean): BuiltQuery;
10
+ export declare function buildInsertMutation(entityName: string, entityDef: EntityDescriptor, schema: SchemaDescriptor, returning: Record<string, unknown> | undefined, isSingle: boolean): BuiltQuery;
11
+ export declare function buildUpdateMutation(entityName: string, entityDef: EntityDescriptor, schema: SchemaDescriptor, returning: Record<string, unknown> | undefined, hasWhere: boolean): BuiltQuery;
12
+ export declare function buildDeleteMutation(entityName: string, entityDef: EntityDescriptor, schema: SchemaDescriptor, returning: Record<string, unknown> | undefined, hasWhere: boolean): BuiltQuery;
@@ -0,0 +1,15 @@
1
+ import type { SchemaDescriptor } from './types';
2
+ export type ClientSchemaConfig = {
3
+ mutations?: boolean;
4
+ suffixes?: {
5
+ list?: string;
6
+ single?: string;
7
+ };
8
+ tables?: {
9
+ exclude?: readonly string[];
10
+ };
11
+ pruneRelations?: Record<string, false | 'leaf' | {
12
+ only: string[];
13
+ }>;
14
+ };
15
+ export declare function buildSchemaDescriptor(schema: Record<string, unknown>, config?: ClientSchemaConfig): SchemaDescriptor;
package/types.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ export type RelationDef = {
2
+ entity: string;
3
+ type: 'one' | 'many';
4
+ };
5
+ export type EntityDef = {
6
+ fields: Record<string, unknown>;
7
+ relations: Record<string, RelationDef>;
8
+ filters?: Record<string, unknown>;
9
+ insertInput?: Record<string, unknown>;
10
+ updateInput?: Record<string, unknown>;
11
+ orderBy?: Record<string, unknown>;
12
+ };
13
+ export type AnyEntityDefs = Record<string, EntityDef>;
14
+ export type EntityDescriptor = {
15
+ queryName: string;
16
+ queryListName: string;
17
+ countName: string;
18
+ insertName: string;
19
+ insertSingleName: string;
20
+ updateName: string;
21
+ deleteName: string;
22
+ fields: readonly string[];
23
+ relations: Record<string, {
24
+ entity: string;
25
+ type: 'one' | 'many';
26
+ }>;
27
+ };
28
+ export type SchemaDescriptor = Record<string, EntityDescriptor>;
29
+ export type SelectInput<TDefs extends AnyEntityDefs, TEntity extends EntityDef> = {
30
+ [K in keyof TEntity['fields'] | keyof TEntity['relations']]?: K extends keyof TEntity['relations'] ? TEntity['relations'][K] extends RelationDef ? TEntity['relations'][K]['entity'] extends keyof TDefs ? SelectInput<TDefs, TDefs[TEntity['relations'][K]['entity']]> : never : never : K extends keyof TEntity['fields'] ? true : never;
31
+ };
32
+ type Simplify<T> = {
33
+ [K in keyof T]: T[K];
34
+ } & {};
35
+ export type InferResult<TDefs extends AnyEntityDefs, TEntity extends EntityDef, TSelect> = Simplify<InferScalars<TEntity, TSelect> & InferRelations<TDefs, TEntity, TSelect>>;
36
+ type InferScalars<TEntity extends EntityDef, TSelect> = Pick<TEntity['fields'], keyof TSelect & keyof TEntity['fields']>;
37
+ type InferRelations<TDefs extends AnyEntityDefs, TEntity extends EntityDef, TSelect> = {
38
+ [K in keyof TSelect & keyof TEntity['relations'] as TSelect[K] extends Record<string, unknown> ? K : never]: TEntity['relations'][K] extends RelationDef ? TEntity['relations'][K]['entity'] extends keyof TDefs ? TEntity['relations'][K]['type'] extends 'many' ? InferResult<TDefs, TDefs[TEntity['relations'][K]['entity']], TSelect[K]>[] : InferResult<TDefs, TDefs[TEntity['relations'][K]['entity']], TSelect[K]> | null : never : never;
39
+ };
40
+ export type ClientConfig<TSchema extends SchemaDescriptor = SchemaDescriptor> = {
41
+ url: string | (() => string);
42
+ schema: TSchema;
43
+ headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
44
+ };
45
+ export {};