nextjs-hasura-auth 0.1.0 → 0.1.2
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/APOLLO.md +106 -80
- package/GENERATOR.md +4 -5
- package/README.md +75 -14
- package/dist/lib/apollo.d.ts +9 -9
- package/dist/lib/{apollo.js → apollo.jsx} +14 -39
- package/dist/lib/auth.d.ts +16 -0
- package/dist/lib/auth.jsx +159 -0
- package/dist/lib/client.d.ts +82 -0
- package/dist/lib/client.jsx +237 -0
- package/dist/lib/generator.d.ts +2 -7
- package/dist/lib/generator.js +394 -392
- package/dist/lib/hasura-schema.d.ts +1 -0
- package/dist/lib/hasura-schema.js +72 -0
- package/dist/lib/hasura.d.ts +16 -0
- package/dist/lib/hasura.js +102 -0
- package/dist/lib/index.d.ts +4 -0
- package/dist/lib/index.js +4 -0
- package/dist/package.json +22 -5
- package/dist/public/hasura-schema.json +7995 -0
- package/dist/tsconfig.lib.tsbuildinfo +1 -1
- package/package.json +18 -4
@@ -0,0 +1,159 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
9
|
+
});
|
10
|
+
};
|
11
|
+
var __rest = (this && this.__rest) || function (s, e) {
|
12
|
+
var t = {};
|
13
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
14
|
+
t[p] = s[p];
|
15
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
16
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
17
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
18
|
+
t[p[i]] = s[p[i]];
|
19
|
+
}
|
20
|
+
return t;
|
21
|
+
};
|
22
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
23
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
24
|
+
};
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
26
|
+
exports.getTokenFromRequest = getTokenFromRequest;
|
27
|
+
exports.WsClientsManager = WsClientsManager;
|
28
|
+
const debug_1 = __importDefault(require("@/lib/debug"));
|
29
|
+
const jwt_1 = require("next-auth/jwt");
|
30
|
+
const uuid_1 = require("uuid");
|
31
|
+
const debug = (0, debug_1.default)('auth');
|
32
|
+
function getTokenFromRequest(request) {
|
33
|
+
return __awaiter(this, void 0, void 0, function* () {
|
34
|
+
const secureCookie = request.url.startsWith('https');
|
35
|
+
const cookieName = secureCookie
|
36
|
+
? '__Secure-next-auth.session-token'
|
37
|
+
: 'next-auth.session-token';
|
38
|
+
debug(`GET /api/auth: Using cookie name: ${cookieName}, secure: ${secureCookie}`);
|
39
|
+
const token = yield (0, jwt_1.getToken)({
|
40
|
+
req: request, // Cast to any to satisfy getToken, NextRequest works
|
41
|
+
secret: process.env.NEXTAUTH_SECRET,
|
42
|
+
cookieName: cookieName,
|
43
|
+
});
|
44
|
+
return token;
|
45
|
+
});
|
46
|
+
}
|
47
|
+
function WsClientsManager(route = '') {
|
48
|
+
const clientManagerId = route + (0, uuid_1.v4)();
|
49
|
+
debug(`(${clientManagerId}): New WebSocket clients manager established.`);
|
50
|
+
const clients = new Map();
|
51
|
+
return {
|
52
|
+
Client: (client) => {
|
53
|
+
const clientId = (0, uuid_1.v4)();
|
54
|
+
clients.set(clientId, { ws: client });
|
55
|
+
debug(`(${clientManagerId}): New client (${clientId}) connected.`);
|
56
|
+
return clientId;
|
57
|
+
},
|
58
|
+
getToken(request, clientId) {
|
59
|
+
return __awaiter(this, void 0, void 0, function* () {
|
60
|
+
var _a;
|
61
|
+
const cookieHeader = request.headers.cookie;
|
62
|
+
const userAgent = request.headers['user-agent'];
|
63
|
+
const forwardedProto = request.headers['x-forwarded-proto'];
|
64
|
+
const connectionEncrypted = (_a = request.connection) === null || _a === void 0 ? void 0 : _a.encrypted;
|
65
|
+
debug(`${clientManagerId}: (${clientId}): Incoming request details - URL: ${request.url}, Method: ${request.method}, User-Agent: ${userAgent}`);
|
66
|
+
debug(`${clientManagerId}: (${clientId}): Incoming headers:`, request.headers);
|
67
|
+
debug(`${clientManagerId}: (${clientId}): Connection encrypted: ${connectionEncrypted}`);
|
68
|
+
debug(`${clientManagerId}: (${clientId}): X-Forwarded-Proto: ${forwardedProto}`);
|
69
|
+
debug(`${clientManagerId}: (${clientId}): Full cookie header:`, cookieHeader || 'No cookies header');
|
70
|
+
// Determine secure context and cookie name
|
71
|
+
const isSecure = forwardedProto === 'https' || connectionEncrypted;
|
72
|
+
const sessionCookieName = isSecure
|
73
|
+
? '__Secure-next-auth.session-token'
|
74
|
+
: 'next-auth.session-token';
|
75
|
+
debug(`${clientManagerId}: (${clientId}): Determined secure context: ${isSecure}`);
|
76
|
+
debug(`${clientManagerId}: (${clientId}): Expecting session cookie name: ${sessionCookieName}`);
|
77
|
+
let token = null;
|
78
|
+
let payload = null;
|
79
|
+
let userId = null;
|
80
|
+
const rawToken = false; // Keep false
|
81
|
+
try {
|
82
|
+
debug(`SOCKET /api/auth (${clientId}): Preparing adapted request for getToken (raw: ${rawToken})...`);
|
83
|
+
const parsedCookies = request.headers.cookie ?
|
84
|
+
Object.fromEntries(request.headers.cookie.split('; ').map(c => {
|
85
|
+
const [key, ...val] = c.split('=');
|
86
|
+
return [key, decodeURIComponent(val.join('='))];
|
87
|
+
}))
|
88
|
+
: {};
|
89
|
+
debug(`SOCKET /api/auth (${clientId}): Parsed cookies object:`, parsedCookies);
|
90
|
+
const adaptedReq = {
|
91
|
+
headers: request.headers,
|
92
|
+
cookies: parsedCookies,
|
93
|
+
url: request.url || '',
|
94
|
+
method: request.method || 'GET',
|
95
|
+
};
|
96
|
+
debug(`SOCKET /api/auth (${clientId}): Final adapted request object for getToken:`, adaptedReq);
|
97
|
+
const getTokenParams = {
|
98
|
+
req: adaptedReq,
|
99
|
+
secret: process.env.NEXTAUTH_SECRET,
|
100
|
+
cookieName: sessionCookieName,
|
101
|
+
raw: rawToken, // Should be false now
|
102
|
+
};
|
103
|
+
debug(`${clientManagerId}: (${clientId}): Calling getToken with params:`, {
|
104
|
+
cookieName: getTokenParams.cookieName,
|
105
|
+
raw: getTokenParams.raw,
|
106
|
+
secretProvided: !!getTokenParams.secret,
|
107
|
+
});
|
108
|
+
token = yield (0, jwt_1.getToken)(getTokenParams);
|
109
|
+
debug(`${clientManagerId}: (${clientId}): getToken result received.`);
|
110
|
+
debug(`${clientManagerId}: (${clientId}): Decoded token value from getToken:`, token);
|
111
|
+
debug(`${clientManagerId}: (${clientId}): getToken result type: ${typeof token}, isNull: ${token === null}`);
|
112
|
+
if (token && typeof token === 'object' && token.sub) {
|
113
|
+
payload = token;
|
114
|
+
userId = payload.sub;
|
115
|
+
debug(`${clientManagerId}: (${clientId}): User ${userId} authenticated via decoded token from getToken.`);
|
116
|
+
}
|
117
|
+
else {
|
118
|
+
debug(`${clientManagerId}: (${clientId}): No valid token found or token is not an object with sub property.`);
|
119
|
+
}
|
120
|
+
return token;
|
121
|
+
}
|
122
|
+
catch (error) {
|
123
|
+
debug(`${clientManagerId}: (${clientId}): Error preparing adapted request for getToken:`, error);
|
124
|
+
throw error;
|
125
|
+
}
|
126
|
+
});
|
127
|
+
},
|
128
|
+
parseUser(request, clientId) {
|
129
|
+
return __awaiter(this, void 0, void 0, function* () {
|
130
|
+
const token = yield this.getToken(request, clientId);
|
131
|
+
if (token && typeof token === 'object' && token.sub) {
|
132
|
+
const _a = token, { accessToken } = _a, user = __rest(_a, ["accessToken"]);
|
133
|
+
const client = clients.get(clientId);
|
134
|
+
if (client) {
|
135
|
+
client.userId = token.sub;
|
136
|
+
client.user = user;
|
137
|
+
clients.set(clientId, client);
|
138
|
+
debug(`${clientManagerId}: (${clientId}): Client parsed and updated.`);
|
139
|
+
}
|
140
|
+
else {
|
141
|
+
debug(`${clientManagerId}: (${clientId}): No client found in clients map.`);
|
142
|
+
}
|
143
|
+
return user;
|
144
|
+
}
|
145
|
+
else {
|
146
|
+
debug(`${clientManagerId}: (${clientId}): No valid token found or token is not an object with sub property.`);
|
147
|
+
}
|
148
|
+
return null;
|
149
|
+
});
|
150
|
+
},
|
151
|
+
delete(clientId) {
|
152
|
+
clients.delete(clientId);
|
153
|
+
debug(`${clientManagerId}: (${clientId}): Client deleted from clients map.`);
|
154
|
+
},
|
155
|
+
getClient(clientId) {
|
156
|
+
return clients.get(clientId);
|
157
|
+
}
|
158
|
+
};
|
159
|
+
}
|
@@ -0,0 +1,82 @@
|
|
1
|
+
import { ApolloClient, ApolloError, FetchResult, Observable, OperationVariables, useQuery as useApolloQuery, useSubscription as useApolloSubscription } from '@apollo/client';
|
2
|
+
import { GenerateOptions, GenerateResult } from './generator';
|
3
|
+
/**
|
4
|
+
* Represents the result structure from Apollo hooks, including potential errors.
|
5
|
+
*/
|
6
|
+
export interface HookResult<TData = any> {
|
7
|
+
loading: boolean;
|
8
|
+
data?: TData;
|
9
|
+
error?: ApolloError;
|
10
|
+
[key: string]: any;
|
11
|
+
generatedQuery?: GenerateResult['query'];
|
12
|
+
generatedVariables?: GenerateResult['variables'];
|
13
|
+
}
|
14
|
+
export declare class Client {
|
15
|
+
private apolloClient;
|
16
|
+
private generate;
|
17
|
+
constructor(apolloClient: ApolloClient<any>);
|
18
|
+
/**
|
19
|
+
* Executes a GraphQL query (select operation).
|
20
|
+
* @param options - Options for generating the query.
|
21
|
+
* @returns Promise resolving with the query result data.
|
22
|
+
* @throws ApolloError if the query fails or returns GraphQL errors.
|
23
|
+
*/
|
24
|
+
select<TData = any>(options: Omit<GenerateOptions, 'operation'>): Promise<TData>;
|
25
|
+
/**
|
26
|
+
* Executes a GraphQL insert mutation.
|
27
|
+
* @param options - Options for generating the mutation.
|
28
|
+
* @returns Promise resolving with the mutation result data.
|
29
|
+
* @throws ApolloError if the mutation fails or returns GraphQL errors.
|
30
|
+
*/
|
31
|
+
insert<TData = any>(options: Omit<GenerateOptions, 'operation'>): Promise<TData>;
|
32
|
+
/**
|
33
|
+
* Executes a GraphQL update mutation.
|
34
|
+
* @param options - Options for generating the mutation.
|
35
|
+
* @returns Promise resolving with the mutation result data.
|
36
|
+
* @throws ApolloError if the mutation fails or returns GraphQL errors.
|
37
|
+
*/
|
38
|
+
update<TData = any>(options: Omit<GenerateOptions, 'operation'>): Promise<TData>;
|
39
|
+
/**
|
40
|
+
* Executes a GraphQL delete mutation.
|
41
|
+
* @param options - Options for generating the mutation.
|
42
|
+
* @returns Promise resolving with the mutation result data.
|
43
|
+
* @throws ApolloError if the mutation fails or returns GraphQL errors.
|
44
|
+
*/
|
45
|
+
delete<TData = any>(options: Omit<GenerateOptions, 'operation'>): Promise<TData>;
|
46
|
+
/**
|
47
|
+
* Initiates a GraphQL subscription.
|
48
|
+
* @param options - Options for generating the subscription.
|
49
|
+
* @returns An Observable for the subscription results.
|
50
|
+
*/
|
51
|
+
subscribe<TData = any, TVariables extends OperationVariables = OperationVariables>(options: Omit<GenerateOptions, 'operation'>): Observable<FetchResult<TData>>;
|
52
|
+
}
|
53
|
+
/**
|
54
|
+
* Hook to get the Apollo Client instance.
|
55
|
+
* Prefers the explicitly provided client, falls back to context, throws if none found.
|
56
|
+
* @param providedClient - An optional ApolloClient instance.
|
57
|
+
* @returns The ApolloClient instance.
|
58
|
+
* @throws Error if no client is found.
|
59
|
+
*/
|
60
|
+
export declare function useClient(providedClient?: ApolloClient<any> | null): ApolloClient<any>;
|
61
|
+
/**
|
62
|
+
* Hook to perform a GraphQL query using the generator.
|
63
|
+
* @template TData - The expected data type.
|
64
|
+
* @param options - Options for the generator (operation is automatically set to 'query').
|
65
|
+
* @param providedClient - Optional ApolloClient instance to use instead of context.
|
66
|
+
* @param hookOptions - Optional additional options passed directly to Apollo's useQuery hook.
|
67
|
+
* @returns An object containing loading state, data, error, and the generated query/variables.
|
68
|
+
*/
|
69
|
+
export declare function useQuery<TData = any>(options: Omit<GenerateOptions, 'operation'>, providedClient?: ApolloClient<any> | null, hookOptions?: Omit<Parameters<typeof useApolloQuery>[1], 'variables' | 'client' | 'query'>): HookResult<TData>;
|
70
|
+
/** Alias for useQuery */
|
71
|
+
export declare const useSelect: typeof useQuery;
|
72
|
+
/**
|
73
|
+
* Hook to perform a GraphQL subscription using the generator.
|
74
|
+
* @template TData - The expected data type.
|
75
|
+
* @param options - Options for the generator (operation is automatically set to 'subscription').
|
76
|
+
* @param providedClient - Optional ApolloClient instance to use instead of context.
|
77
|
+
* @param hookOptions - Optional additional options passed directly to Apollo's useSubscription hook.
|
78
|
+
* @returns An object containing loading state, data, error, and the generated query/variables.
|
79
|
+
*/
|
80
|
+
export declare function useSubscription<TData = any>(options: Omit<GenerateOptions, 'operation'>, providedClient?: ApolloClient<any> | null, hookOptions?: Omit<Parameters<typeof useApolloSubscription>[1], 'variables' | 'client' | 'query'>): HookResult<TData>;
|
81
|
+
/** Alias for useSubscription */
|
82
|
+
export declare const useSubscribe: typeof useSubscription;
|
@@ -0,0 +1,237 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
9
|
+
});
|
10
|
+
};
|
11
|
+
var __rest = (this && this.__rest) || function (s, e) {
|
12
|
+
var t = {};
|
13
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
14
|
+
t[p] = s[p];
|
15
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
16
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
17
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
18
|
+
t[p[i]] = s[p[i]];
|
19
|
+
}
|
20
|
+
return t;
|
21
|
+
};
|
22
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
23
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
24
|
+
};
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
26
|
+
exports.useSubscribe = exports.useSelect = exports.Client = void 0;
|
27
|
+
exports.useClient = useClient;
|
28
|
+
exports.useQuery = useQuery;
|
29
|
+
exports.useSubscription = useSubscription;
|
30
|
+
const client_1 = require("@apollo/client");
|
31
|
+
const react_1 = require("react");
|
32
|
+
const generator_1 = __importDefault(require("./generator")); // Assuming generator exports the function directly
|
33
|
+
const debug_1 = __importDefault(require("./debug"));
|
34
|
+
const debug = (0, debug_1.default)('nha:client');
|
35
|
+
class Client {
|
36
|
+
constructor(apolloClient) {
|
37
|
+
if (!apolloClient) {
|
38
|
+
throw new Error('❌ ApolloClient instance must be provided to the Client constructor.');
|
39
|
+
}
|
40
|
+
this.apolloClient = apolloClient;
|
41
|
+
this.generate = generator_1.default; // Use the imported generator function
|
42
|
+
debug('Client class initialized with ApolloClient instance.');
|
43
|
+
}
|
44
|
+
/**
|
45
|
+
* Executes a GraphQL query (select operation).
|
46
|
+
* @param options - Options for generating the query.
|
47
|
+
* @returns Promise resolving with the query result data.
|
48
|
+
* @throws ApolloError if the query fails or returns GraphQL errors.
|
49
|
+
*/
|
50
|
+
select(options) {
|
51
|
+
return __awaiter(this, void 0, void 0, function* () {
|
52
|
+
debug('Executing select with options:', options);
|
53
|
+
const generated = this.generate(Object.assign(Object.assign({}, options), { operation: 'query' }));
|
54
|
+
try {
|
55
|
+
const result = yield this.apolloClient.query({
|
56
|
+
query: generated.query,
|
57
|
+
variables: generated.variables,
|
58
|
+
fetchPolicy: 'network-only', // Ensure fresh data for direct calls
|
59
|
+
});
|
60
|
+
if (result.errors) {
|
61
|
+
debug('GraphQL errors during select:', result.errors);
|
62
|
+
throw new client_1.ApolloError({ graphQLErrors: result.errors });
|
63
|
+
}
|
64
|
+
debug('Select successful, returning data:', result.data);
|
65
|
+
return result.data;
|
66
|
+
}
|
67
|
+
catch (error) {
|
68
|
+
debug('Error during select:', error);
|
69
|
+
throw error; // Re-throw original error (could be ApolloError or network error)
|
70
|
+
}
|
71
|
+
});
|
72
|
+
}
|
73
|
+
/**
|
74
|
+
* Executes a GraphQL insert mutation.
|
75
|
+
* @param options - Options for generating the mutation.
|
76
|
+
* @returns Promise resolving with the mutation result data.
|
77
|
+
* @throws ApolloError if the mutation fails or returns GraphQL errors.
|
78
|
+
*/
|
79
|
+
insert(options) {
|
80
|
+
return __awaiter(this, void 0, void 0, function* () {
|
81
|
+
var _a;
|
82
|
+
debug('Executing insert with options:', options);
|
83
|
+
const generated = this.generate(Object.assign(Object.assign({}, options), { operation: 'insert' }));
|
84
|
+
try {
|
85
|
+
const result = yield this.apolloClient.mutate({
|
86
|
+
mutation: generated.query,
|
87
|
+
variables: generated.variables,
|
88
|
+
});
|
89
|
+
if (result.errors) {
|
90
|
+
debug('GraphQL errors during insert:', result.errors);
|
91
|
+
throw new client_1.ApolloError({ graphQLErrors: result.errors });
|
92
|
+
}
|
93
|
+
// Check if data exists, otherwise return an empty object or handle as needed
|
94
|
+
const returnData = (_a = result.data) !== null && _a !== void 0 ? _a : {};
|
95
|
+
debug('Insert successful, returning data:', returnData);
|
96
|
+
return returnData;
|
97
|
+
}
|
98
|
+
catch (error) {
|
99
|
+
debug('Error during insert:', error);
|
100
|
+
throw error;
|
101
|
+
}
|
102
|
+
});
|
103
|
+
}
|
104
|
+
/**
|
105
|
+
* Executes a GraphQL update mutation.
|
106
|
+
* @param options - Options for generating the mutation.
|
107
|
+
* @returns Promise resolving with the mutation result data.
|
108
|
+
* @throws ApolloError if the mutation fails or returns GraphQL errors.
|
109
|
+
*/
|
110
|
+
update(options) {
|
111
|
+
return __awaiter(this, void 0, void 0, function* () {
|
112
|
+
var _a;
|
113
|
+
debug('Executing update with options:', options);
|
114
|
+
const generated = this.generate(Object.assign(Object.assign({}, options), { operation: 'update' }));
|
115
|
+
try {
|
116
|
+
const result = yield this.apolloClient.mutate({
|
117
|
+
mutation: generated.query,
|
118
|
+
variables: generated.variables,
|
119
|
+
});
|
120
|
+
if (result.errors) {
|
121
|
+
debug('GraphQL errors during update:', result.errors);
|
122
|
+
throw new client_1.ApolloError({ graphQLErrors: result.errors });
|
123
|
+
}
|
124
|
+
const returnData = (_a = result.data) !== null && _a !== void 0 ? _a : {};
|
125
|
+
debug('Update successful, returning data:', returnData);
|
126
|
+
return returnData;
|
127
|
+
}
|
128
|
+
catch (error) {
|
129
|
+
debug('Error during update:', error);
|
130
|
+
throw error;
|
131
|
+
}
|
132
|
+
});
|
133
|
+
}
|
134
|
+
/**
|
135
|
+
* Executes a GraphQL delete mutation.
|
136
|
+
* @param options - Options for generating the mutation.
|
137
|
+
* @returns Promise resolving with the mutation result data.
|
138
|
+
* @throws ApolloError if the mutation fails or returns GraphQL errors.
|
139
|
+
*/
|
140
|
+
delete(options) {
|
141
|
+
return __awaiter(this, void 0, void 0, function* () {
|
142
|
+
var _a;
|
143
|
+
debug('Executing delete with options:', options);
|
144
|
+
const generated = this.generate(Object.assign(Object.assign({}, options), { operation: 'delete' }));
|
145
|
+
try {
|
146
|
+
const result = yield this.apolloClient.mutate({
|
147
|
+
mutation: generated.query,
|
148
|
+
variables: generated.variables,
|
149
|
+
});
|
150
|
+
if (result.errors) {
|
151
|
+
debug('GraphQL errors during delete:', result.errors);
|
152
|
+
throw new client_1.ApolloError({ graphQLErrors: result.errors });
|
153
|
+
}
|
154
|
+
const returnData = (_a = result.data) !== null && _a !== void 0 ? _a : {};
|
155
|
+
debug('Delete successful, returning data:', returnData);
|
156
|
+
return returnData;
|
157
|
+
}
|
158
|
+
catch (error) {
|
159
|
+
debug('Error during delete:', error);
|
160
|
+
throw error;
|
161
|
+
}
|
162
|
+
});
|
163
|
+
}
|
164
|
+
/**
|
165
|
+
* Initiates a GraphQL subscription.
|
166
|
+
* @param options - Options for generating the subscription.
|
167
|
+
* @returns An Observable for the subscription results.
|
168
|
+
*/
|
169
|
+
subscribe(options) {
|
170
|
+
debug('Initiating subscribe with options:', options);
|
171
|
+
const generated = this.generate(Object.assign(Object.assign({}, options), { operation: 'subscription' }));
|
172
|
+
return this.apolloClient.subscribe({
|
173
|
+
query: generated.query,
|
174
|
+
variables: generated.variables,
|
175
|
+
});
|
176
|
+
}
|
177
|
+
}
|
178
|
+
exports.Client = Client;
|
179
|
+
// --- React Hooks ---
|
180
|
+
/**
|
181
|
+
* Hook to get the Apollo Client instance.
|
182
|
+
* Prefers the explicitly provided client, falls back to context, throws if none found.
|
183
|
+
* @param providedClient - An optional ApolloClient instance.
|
184
|
+
* @returns The ApolloClient instance.
|
185
|
+
* @throws Error if no client is found.
|
186
|
+
*/
|
187
|
+
function useClient(providedClient) {
|
188
|
+
const ApolloContext = (0, client_1.getApolloContext)();
|
189
|
+
const contextValue = (0, react_1.useContext)(ApolloContext);
|
190
|
+
const contextClient = contextValue === null || contextValue === void 0 ? void 0 : contextValue.client;
|
191
|
+
const client = providedClient !== null && providedClient !== void 0 ? providedClient : contextClient;
|
192
|
+
if (!client) {
|
193
|
+
throw new Error('❌ useClient: No ApolloClient instance found. Provide one directly or ensure the component is wrapped in an ApolloProvider.');
|
194
|
+
}
|
195
|
+
return client;
|
196
|
+
}
|
197
|
+
/**
|
198
|
+
* Hook to perform a GraphQL query using the generator.
|
199
|
+
* @template TData - The expected data type.
|
200
|
+
* @param options - Options for the generator (operation is automatically set to 'query').
|
201
|
+
* @param providedClient - Optional ApolloClient instance to use instead of context.
|
202
|
+
* @param hookOptions - Optional additional options passed directly to Apollo's useQuery hook.
|
203
|
+
* @returns An object containing loading state, data, error, and the generated query/variables.
|
204
|
+
*/
|
205
|
+
function useQuery(options, providedClient, hookOptions) {
|
206
|
+
// Memoize generator options based on a stable string representation
|
207
|
+
// Important: Ensure options object structure is consistent or use a deep-stable stringify
|
208
|
+
const optionsString = (0, react_1.useMemo)(() => JSON.stringify(options), [options]);
|
209
|
+
const memoizedOptions = (0, react_1.useMemo)(() => JSON.parse(optionsString), [optionsString]);
|
210
|
+
const client = useClient(providedClient);
|
211
|
+
const generated = (0, react_1.useMemo)(() => (0, generator_1.default)(Object.assign(Object.assign({}, memoizedOptions), { operation: 'query' })), [memoizedOptions] // Depend on the memoized options object
|
212
|
+
);
|
213
|
+
const _a = (0, client_1.useQuery)(generated.query, Object.assign({ client: client, variables: generated.variables }, hookOptions)), { loading, error, data } = _a, rest = __rest(_a, ["loading", "error", "data"]);
|
214
|
+
// Combine Apollo results with generator info
|
215
|
+
return Object.assign(Object.assign({ loading, error, data }, rest), { generatedQuery: generated.query, generatedVariables: generated.variables });
|
216
|
+
}
|
217
|
+
/** Alias for useQuery */
|
218
|
+
exports.useSelect = useQuery;
|
219
|
+
/**
|
220
|
+
* Hook to perform a GraphQL subscription using the generator.
|
221
|
+
* @template TData - The expected data type.
|
222
|
+
* @param options - Options for the generator (operation is automatically set to 'subscription').
|
223
|
+
* @param providedClient - Optional ApolloClient instance to use instead of context.
|
224
|
+
* @param hookOptions - Optional additional options passed directly to Apollo's useSubscription hook.
|
225
|
+
* @returns An object containing loading state, data, error, and the generated query/variables.
|
226
|
+
*/
|
227
|
+
function useSubscription(options, providedClient, hookOptions) {
|
228
|
+
// Memoize generator options
|
229
|
+
const optionsString = (0, react_1.useMemo)(() => JSON.stringify(options), [options]);
|
230
|
+
const memoizedOptions = (0, react_1.useMemo)(() => JSON.parse(optionsString), [optionsString]);
|
231
|
+
const client = useClient(providedClient);
|
232
|
+
const generated = (0, react_1.useMemo)(() => (0, generator_1.default)(Object.assign(Object.assign({}, memoizedOptions), { operation: 'subscription' })), [memoizedOptions]);
|
233
|
+
const _a = (0, client_1.useSubscription)(generated.query, Object.assign({ client: client, variables: generated.variables }, hookOptions)), { loading, error, data } = _a, rest = __rest(_a, ["loading", "error", "data"]);
|
234
|
+
return Object.assign(Object.assign({ loading, error, data }, rest), { generatedQuery: generated.query, generatedVariables: generated.variables });
|
235
|
+
}
|
236
|
+
/** Alias for useSubscription */
|
237
|
+
exports.useSubscribe = useSubscription;
|
package/dist/lib/generator.d.ts
CHANGED
@@ -23,11 +23,6 @@ export interface GenerateResult {
|
|
23
23
|
variables: Record<string, any>;
|
24
24
|
varCounter: number;
|
25
25
|
}
|
26
|
-
/**
|
27
|
-
* Creates a GraphQL query generator based on the provided schema.
|
28
|
-
*
|
29
|
-
* @param schema - The GraphQL schema in schema.json format.
|
30
|
-
* @returns A function to generate queries.
|
31
|
-
*/
|
32
26
|
export declare function Generator(schema: any): (opts: GenerateOptions) => GenerateResult;
|
33
|
-
|
27
|
+
declare const _default: (opts: GenerateOptions) => GenerateResult;
|
28
|
+
export default _default;
|