@vrplatform/graphql 1.0.8 → 1.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.
Files changed (88) hide show
  1. package/build/main/client/headers.d.ts +3 -0
  2. package/build/main/client/headers.js +42 -0
  3. package/build/main/client/index.d.ts +13 -0
  4. package/build/main/client/index.js +103 -0
  5. package/build/main/client/subscription.d.ts +3 -0
  6. package/build/main/client/subscription.js +29 -0
  7. package/build/main/common/account.d.ts +2 -0
  8. package/build/main/common/account.js +7 -0
  9. package/build/main/common/address.d.ts +9 -0
  10. package/build/main/common/address.js +2 -0
  11. package/build/main/common/bank-record.d.ts +2 -0
  12. package/build/main/common/bank-record.js +7 -0
  13. package/build/main/common/index.d.ts +5 -0
  14. package/build/main/common/index.js +21 -0
  15. package/build/main/common/listings.d.ts +4 -0
  16. package/build/main/common/listings.js +99 -0
  17. package/build/main/common/tenant.d.ts +19 -0
  18. package/build/main/common/tenant.js +85 -0
  19. package/build/main/error.d.ts +2 -0
  20. package/build/main/error.js +6 -0
  21. package/build/main/gqty/index.d.ts +7 -0
  22. package/build/main/gqty/index.js +48 -0
  23. package/build/main/gqty/schema.generated.d.ts +39464 -46636
  24. package/build/main/gqty/schema.generated.js +10450 -14093
  25. package/build/main/index.d.ts +4 -14
  26. package/build/main/index.js +7 -75
  27. package/build/main/tsconfig.main.tsbuildinfo +1 -1
  28. package/build/main/types.d.ts +5 -6
  29. package/build/main/wrap.d.ts +12 -0
  30. package/build/main/wrap.js +47 -0
  31. package/build/module/client/headers.d.ts +3 -0
  32. package/build/module/client/headers.js +39 -0
  33. package/build/module/client/index.d.ts +13 -0
  34. package/build/module/client/index.js +98 -0
  35. package/build/module/client/subscription.d.ts +3 -0
  36. package/build/module/client/subscription.js +26 -0
  37. package/build/module/common/account.d.ts +2 -0
  38. package/build/module/common/account.js +4 -0
  39. package/build/module/common/address.d.ts +9 -0
  40. package/build/module/common/address.js +1 -0
  41. package/build/module/common/bank-record.d.ts +2 -0
  42. package/build/module/common/bank-record.js +4 -0
  43. package/build/module/common/index.d.ts +5 -0
  44. package/build/module/common/index.js +5 -0
  45. package/build/module/common/listings.d.ts +4 -0
  46. package/build/module/common/listings.js +93 -0
  47. package/build/module/common/tenant.d.ts +19 -0
  48. package/build/module/common/tenant.js +77 -0
  49. package/build/module/error.d.ts +2 -0
  50. package/build/module/error.js +2 -0
  51. package/build/module/gqty/index.d.ts +7 -0
  52. package/build/module/gqty/index.js +41 -0
  53. package/build/module/gqty/schema.generated.d.ts +39464 -46636
  54. package/build/module/gqty/schema.generated.js +10450 -14093
  55. package/build/module/index.d.ts +4 -14
  56. package/build/module/index.js +4 -72
  57. package/build/module/tsconfig.esm.tsbuildinfo +1 -1
  58. package/build/module/types.d.ts +5 -6
  59. package/build/module/wrap.d.ts +12 -0
  60. package/build/module/wrap.js +44 -0
  61. package/package.json +25 -35
  62. package/src/client/headers.ts +51 -0
  63. package/src/client/index.ts +152 -0
  64. package/src/client/subscription.ts +34 -0
  65. package/src/common/account.ts +6 -0
  66. package/src/common/address.ts +9 -0
  67. package/src/common/bank-record.ts +6 -0
  68. package/src/common/index.ts +5 -0
  69. package/src/common/listings.ts +106 -0
  70. package/src/common/tenant.ts +101 -0
  71. package/src/error.ts +1 -0
  72. package/src/gqty/index.ts +62 -0
  73. package/src/gqty/schema.generated.d.ts +39464 -46636
  74. package/src/gqty/schema.generated.js +10472 -14099
  75. package/src/index.ts +9 -94
  76. package/src/types.ts +6 -10
  77. package/src/wrap.ts +67 -0
  78. package/LICENSE +0 -3
  79. package/build/main/create-client.d.ts +0 -6
  80. package/build/main/create-client.js +0 -107
  81. package/build/main/gqty/error.d.ts +0 -6
  82. package/build/main/gqty/error.js +0 -48
  83. package/build/module/create-client.d.ts +0 -6
  84. package/build/module/create-client.js +0 -104
  85. package/build/module/gqty/error.d.ts +0 -6
  86. package/build/module/gqty/error.js +0 -40
  87. package/src/create-client.ts +0 -120
  88. package/src/gqty/error.ts +0 -54
package/src/index.ts CHANGED
@@ -1,95 +1,10 @@
1
- import { useHasuraClientInner } from './create-client';
2
-
3
- export { useHasuraClientInner } from './create-client';
1
+ export {
2
+ GQtyClient,
3
+ GQtyError,
4
+ ResolveOptions,
5
+ SubscriptionsClient,
6
+ } from 'gqty';
7
+ export { type HasuraClient, useHasuraClient } from './client';
8
+ export * from './common';
4
9
  export * from './gqty';
5
- export { GQtyError } from 'gqty';
6
-
7
- import type { LegacyResolveOptions } from 'gqty';
8
- import type { Mutation, Query, Subscription } from './gqty';
9
- import type { GqlAuthParam } from './types';
10
-
11
- export type ResolveOptionsWithSession<T> = LegacyResolveOptions<T>;
12
-
13
- export type HasuraClient = ReturnType<typeof useHasuraClient>;
14
-
15
- export function useHasuraClient(args?: GqlAuthParam) {
16
- const { client, subscriptionsClient } = useHasuraClientInner(args);
17
- const retries = args.retries || 3;
18
- return {
19
- client,
20
- subscriptionsClient,
21
- async mutate<T = unknown>(
22
- resolved: (sub: Mutation) => T,
23
- options?: ResolveOptionsWithSession<T>
24
- ) {
25
- if (!options) options = {};
26
- if (options.noCache === undefined) options.noCache = true;
27
-
28
- let err: any;
29
- for (let tries = 1; tries <= retries; tries++) {
30
- try {
31
- const result = await client.resolve(
32
- ({ mutation }) => resolved(mutation),
33
- options
34
- );
35
- return result;
36
- } catch (error: any) {
37
- err = error;
38
- if (error.message !== 'database query error') break;
39
- await new Promise((resolve) =>
40
- setTimeout(resolve, 1_000 * tries + 1_000)
41
- );
42
- }
43
- }
44
- if (args.onError) throw args.onError(err) || err;
45
- throw err;
46
- },
47
- async query<T = unknown>(
48
- resolved: (sub: Query) => T,
49
- options?: ResolveOptionsWithSession<T>
50
- ) {
51
- let err: any;
52
- for (let tries = 1; tries <= retries; tries++) {
53
- try {
54
- const result = await client.resolve(
55
- ({ query }) => resolved(query),
56
- options
57
- );
58
- return result;
59
- } catch (error: any) {
60
- err = error;
61
- if (error.message !== 'database query error') break;
62
- await new Promise((resolve) =>
63
- setTimeout(resolve, 1_000 * tries + 1_000)
64
- );
65
- }
66
- }
67
- if (args.onError) throw args.onError(err) || err;
68
- throw err;
69
- },
70
- subscribe<T = unknown>(
71
- resolved: (sub: Subscription) => T,
72
- onData: (data: T, unsubscribeFn: () => Promise<void>) => void,
73
- onError?: (err: Error, unsubscribeFn: () => Promise<void>) => void
74
- ) {
75
- if (!subscriptionsClient) throw new Error('Subscriptions not enabled');
76
- let unsub: undefined | (() => Promise<void>);
77
-
78
- const stop = async () => {
79
- if (!unsub) return;
80
- await unsub().catch(() => undefined);
81
- };
82
-
83
- client.resolved(() => resolved(client.subscription), {
84
- onSubscription(event) {
85
- if (event.unsubscribe) unsub = event.unsubscribe;
86
-
87
- if (event.type === 'data') onData(event.data, stop);
88
- else if (event.type === 'with-errors' && onError)
89
- onError(event.error, stop);
90
- },
91
- });
92
- return stop;
93
- },
94
- };
95
- }
10
+ export { type ResolveOptionsWithSession, wrapGraphQLClient } from './wrap';
package/src/types.ts CHANGED
@@ -1,18 +1,14 @@
1
1
  export type Headers = { [s: string]: string };
2
+ export type AllowedHeaders =
3
+ | { [s: string]: string }
4
+ | (() => Headers)
5
+ | (() => Promise<Headers>);
2
6
  export type GqlAuthParam = {
3
7
  accessToken?: string;
4
8
  secret?: string;
5
- headers?:
6
- | { [s: string]: string }
7
- | (() => Headers)
8
- | (() => Promise<Headers>);
9
- fetch?: any;
10
- // normalization?: boolean;
9
+ headers?: AllowedHeaders;
11
10
  subscriptions?: boolean;
12
11
  uri?: string;
13
- // cache?: boolean;
14
- onError?: (err: Error) => any;
15
- /* Retry options, default is 3 times */
16
- retries?: number;
17
12
  auditUserId?: string;
13
+ credentials?: RequestCredentials;
18
14
  };
package/src/wrap.ts ADDED
@@ -0,0 +1,67 @@
1
+ import type { GQtyClient, ResolveOptions, SubscriptionsClient } from 'gqty';
2
+ import type { GeneratedSchema } from './gqty';
3
+
4
+ export type ResolveOptionsWithSession<T> = ResolveOptions<T>;
5
+
6
+ type Client = GQtyClient<GeneratedSchema>;
7
+ export function wrapGraphQLClient(
8
+ getClient: () => Client,
9
+ subscriptionsClient?: SubscriptionsClient
10
+ ) {
11
+ return {
12
+ get client() {
13
+ return getClient();
14
+ },
15
+ subscriptionsClient,
16
+ async mutate<T = unknown>(
17
+ resolved: (sub: Client['mutation']) => T,
18
+ options?: ResolveOptionsWithSession<T>
19
+ ) {
20
+ if (!options) options = {};
21
+ if (options.noCache === undefined) options.noCache = true;
22
+
23
+ const client = getClient();
24
+ const result = await client.resolved(
25
+ () => resolved(client.mutation),
26
+ options
27
+ );
28
+ return result;
29
+ },
30
+ async query<T = unknown>(
31
+ resolved: (sub: Client['query']) => T,
32
+ options?: ResolveOptionsWithSession<T>
33
+ ) {
34
+ const client = getClient();
35
+ const result = await client.resolved(
36
+ () => resolved(client.query),
37
+ options
38
+ );
39
+ return result;
40
+ },
41
+ subscribe<T = unknown>(
42
+ resolved: (sub: Client['subscription']) => T,
43
+ onData: (data: T, unsubscribeFn: () => Promise<void>) => void,
44
+ onError?: (err: Error, unsubscribeFn: () => Promise<void>) => void
45
+ ) {
46
+ if (!subscriptionsClient) throw new Error('Subscriptions not enabled');
47
+ let unsub: undefined | (() => Promise<void>);
48
+
49
+ const stop = async () => {
50
+ if (!unsub) return;
51
+ await unsub().catch(() => undefined);
52
+ };
53
+
54
+ const client = getClient();
55
+ client.resolved(() => resolved(client.subscription), {
56
+ onSubscription(event) {
57
+ if (event.unsubscribe) unsub = event.unsubscribe;
58
+
59
+ if (event.type === 'data') onData(event.data, stop);
60
+ else if (event.type === 'with-errors' && onError)
61
+ onError(event.error, stop);
62
+ },
63
+ });
64
+ return stop;
65
+ },
66
+ };
67
+ }
package/LICENSE DELETED
@@ -1,3 +0,0 @@
1
- RESTRICTED
2
-
3
- THE CODE IS NOT MEANT TO BE SHARED WITH ANYONE OUTSIDE THE MAINTAINERS, AS SET IN THE REPOSITORIES GITHUB ACCESS SETTINGS.
@@ -1,6 +0,0 @@
1
- import { type GeneratedSchema } from './gqty';
2
- import type { GqlAuthParam } from './types';
3
- export declare function useHasuraClientInner(args?: Omit<GqlAuthParam, 'retries'>): {
4
- subscriptionsClient: import("graphql-ws").Client;
5
- client: import("gqty").GQtyClient<GeneratedSchema>;
6
- };
@@ -1,107 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.useHasuraClientInner = useHasuraClientInner;
4
- // import fetch from 'cross-fetch';
5
- const gqty_1 = require("gqty");
6
- const graphql_ws_1 = require("graphql-ws");
7
- const constants_1 = require("./constants");
8
- const gqty_2 = require("./gqty");
9
- const error_1 = require("./gqty/error");
10
- function useHasuraClientInner(args) {
11
- const $headers = args && 'headers' in args ? args.headers : undefined;
12
- const $fetch = (args && 'fetch' in args ? args.fetch : undefined) || fetch;
13
- const uri = args?.uri || constants_1.hasuraGraphqlUri;
14
- const getHeaders = async (base) => {
15
- const headers = ($headers && typeof $headers === 'function'
16
- ? await $headers()
17
- : $headers) || {};
18
- if (base)
19
- for (const key in base)
20
- headers[key] = base[key];
21
- if (args && 'secret' in args && args.secret) {
22
- headers['x-hasura-admin-secret'] = args.secret;
23
- }
24
- else if (args && 'accessToken' in args && args.accessToken) {
25
- headers.authorization = args.accessToken.startsWith('Bearer ')
26
- ? args.accessToken
27
- : `Bearer ${args.accessToken}`;
28
- }
29
- if (args?.auditUserId)
30
- headers['x-hasura-audit-user-id'] = args.auditUserId;
31
- return headers;
32
- };
33
- const queryFetcher = async ({ query, variables, operationName }, fetchOptions) => {
34
- const headers = await getHeaders();
35
- if (fetchOptions?.headers) {
36
- for (const key in fetchOptions.headers) {
37
- headers[key] = fetchOptions.headers[key];
38
- }
39
- }
40
- // Modify "https://finalytic.hasura.app/v1/graphql" if needed
41
- const response = await $fetch('https://finalytic.hasura.app/v1/graphql', {
42
- ...fetchOptions,
43
- method: 'POST',
44
- headers: {
45
- 'Content-Type': 'application/json',
46
- ...headers,
47
- },
48
- body: JSON.stringify({
49
- query,
50
- variables,
51
- operationName,
52
- }),
53
- mode: 'cors',
54
- });
55
- const res = await (0, error_1.defaultResponseHandler)(response);
56
- return res;
57
- };
58
- const subscriptionsClient = args?.subscriptions === true
59
- ? (0, graphql_ws_1.createClient)({
60
- lazy: true,
61
- connectionParams: async () => ({
62
- headers: await getHeaders({
63
- [constants_1.hasuraQueryTypeHeader]: 'subscription',
64
- }),
65
- }),
66
- url() {
67
- const wsUrl = new URL(uri);
68
- wsUrl.protocol = wsUrl.protocol
69
- .replace('https', 'wss')
70
- .replace('http', 'ws');
71
- return wsUrl.href;
72
- },
73
- /*url: () => {
74
- },*/
75
- })
76
- : undefined;
77
- const cache = new gqty_1.Cache(undefined, {
78
- maxAge: 0,
79
- staleWhileRevalidate: 0,
80
- normalization: false,
81
- });
82
- const client = (0, gqty_1.createClient)({
83
- schema: gqty_2.generatedSchema,
84
- scalars: gqty_2.scalarsEnumsHash,
85
- //cache,
86
- cache,
87
- fetchOptions: {
88
- fetcher: queryFetcher,
89
- subscriber: subscriptionsClient,
90
- },
91
- });
92
- /*const client: GQtyClient<GeneratedSchema> = createClient<GeneratedSchema>({
93
- schema: generatedSchema,
94
- scalarsEnumsHash,
95
- queryFetcher,
96
- subscriptionsClient,
97
- normalization: args?.normalization === true,
98
- defaults: {
99
- resolved: {
100
- noCache: args?.cache !== true,
101
- retry: false,
102
- },
103
- },
104
- ...args,
105
- });*/
106
- return { subscriptionsClient, client };
107
- }
@@ -1,6 +0,0 @@
1
- import type { ExecutionResult } from 'graphql';
2
- export declare const defaultResponseHandler: (response: Response) => Promise<ExecutionResult<import("graphql/jsutils/ObjMap").ObjMap<unknown>, import("graphql/jsutils/ObjMap").ObjMap<unknown>>>;
3
- export declare const parseResponse: (response: Response) => Promise<any>;
4
- export declare function assertExecutionResult(input: unknown): asserts input is ExecutionResult;
5
- export declare const isExecutionResult: (input: unknown) => input is ExecutionResult;
6
- export declare const handleResponseErrors: (result: ExecutionResult) => void;
@@ -1,48 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.handleResponseErrors = exports.isExecutionResult = exports.parseResponse = exports.defaultResponseHandler = void 0;
4
- exports.assertExecutionResult = assertExecutionResult;
5
- const gqty_1 = require("gqty");
6
- const defaultResponseHandler = async (response) => {
7
- const result = await (0, exports.parseResponse)(response);
8
- assertExecutionResult(result);
9
- (0, exports.handleResponseErrors)(result);
10
- return result;
11
- };
12
- exports.defaultResponseHandler = defaultResponseHandler;
13
- const parseResponse = async (response) => {
14
- const text = await response.text().then((text) => text.trim() || null);
15
- if (response.status >= 400) {
16
- throw new gqty_1.GQtyError(`Received HTTP ${response.status} from GraphQL endpoint${text
17
- ? `, body: ${text.length > 50 ? `${text.slice(0, 50)}...` : text}`
18
- : ''}.`);
19
- }
20
- if (!text) {
21
- throw new gqty_1.GQtyError('Received an empty response from GraphQL endpoint.');
22
- }
23
- try {
24
- return JSON.parse(text);
25
- }
26
- catch (error) {
27
- throw new gqty_1.GQtyError(`Received malformed JSON response from GraphQL endpoint: ${text.length > 50 ? `${text.slice(0, 50)}...` : text}`);
28
- }
29
- };
30
- exports.parseResponse = parseResponse;
31
- function assertExecutionResult(input) {
32
- if (!(0, exports.isExecutionResult)(input)) {
33
- throw new gqty_1.GQtyError(`Expected response to be an ExecutionResult, received: ${JSON.stringify(input)}`);
34
- }
35
- }
36
- const isExecutionResult = (input) => {
37
- if (typeof input !== 'object' || input === null)
38
- return false;
39
- const value = input;
40
- return 'data' in value || Array.isArray(value.errors);
41
- };
42
- exports.isExecutionResult = isExecutionResult;
43
- const handleResponseErrors = (result) => {
44
- if (result.errors?.length) {
45
- throw gqty_1.GQtyError.fromGraphQLErrors(result.errors);
46
- }
47
- };
48
- exports.handleResponseErrors = handleResponseErrors;
@@ -1,6 +0,0 @@
1
- import { type GeneratedSchema } from './gqty';
2
- import type { GqlAuthParam } from './types';
3
- export declare function useHasuraClientInner(args?: Omit<GqlAuthParam, 'retries'>): {
4
- subscriptionsClient: import("graphql-ws").Client;
5
- client: import("gqty").GQtyClient<GeneratedSchema>;
6
- };
@@ -1,104 +0,0 @@
1
- // import fetch from 'cross-fetch';
2
- import { Cache, createClient } from 'gqty';
3
- import { createClient as createSubscriptionsClient } from 'graphql-ws';
4
- import { hasuraGraphqlUri, hasuraQueryTypeHeader } from './constants';
5
- import { generatedSchema, scalarsEnumsHash, } from './gqty';
6
- import { defaultResponseHandler } from './gqty/error';
7
- export function useHasuraClientInner(args) {
8
- const $headers = args && 'headers' in args ? args.headers : undefined;
9
- const $fetch = (args && 'fetch' in args ? args.fetch : undefined) || fetch;
10
- const uri = args?.uri || hasuraGraphqlUri;
11
- const getHeaders = async (base) => {
12
- const headers = ($headers && typeof $headers === 'function'
13
- ? await $headers()
14
- : $headers) || {};
15
- if (base)
16
- for (const key in base)
17
- headers[key] = base[key];
18
- if (args && 'secret' in args && args.secret) {
19
- headers['x-hasura-admin-secret'] = args.secret;
20
- }
21
- else if (args && 'accessToken' in args && args.accessToken) {
22
- headers.authorization = args.accessToken.startsWith('Bearer ')
23
- ? args.accessToken
24
- : `Bearer ${args.accessToken}`;
25
- }
26
- if (args?.auditUserId)
27
- headers['x-hasura-audit-user-id'] = args.auditUserId;
28
- return headers;
29
- };
30
- const queryFetcher = async ({ query, variables, operationName }, fetchOptions) => {
31
- const headers = await getHeaders();
32
- if (fetchOptions?.headers) {
33
- for (const key in fetchOptions.headers) {
34
- headers[key] = fetchOptions.headers[key];
35
- }
36
- }
37
- // Modify "https://finalytic.hasura.app/v1/graphql" if needed
38
- const response = await $fetch('https://finalytic.hasura.app/v1/graphql', {
39
- ...fetchOptions,
40
- method: 'POST',
41
- headers: {
42
- 'Content-Type': 'application/json',
43
- ...headers,
44
- },
45
- body: JSON.stringify({
46
- query,
47
- variables,
48
- operationName,
49
- }),
50
- mode: 'cors',
51
- });
52
- const res = await defaultResponseHandler(response);
53
- return res;
54
- };
55
- const subscriptionsClient = args?.subscriptions === true
56
- ? createSubscriptionsClient({
57
- lazy: true,
58
- connectionParams: async () => ({
59
- headers: await getHeaders({
60
- [hasuraQueryTypeHeader]: 'subscription',
61
- }),
62
- }),
63
- url() {
64
- const wsUrl = new URL(uri);
65
- wsUrl.protocol = wsUrl.protocol
66
- .replace('https', 'wss')
67
- .replace('http', 'ws');
68
- return wsUrl.href;
69
- },
70
- /*url: () => {
71
- },*/
72
- })
73
- : undefined;
74
- const cache = new Cache(undefined, {
75
- maxAge: 0,
76
- staleWhileRevalidate: 0,
77
- normalization: false,
78
- });
79
- const client = createClient({
80
- schema: generatedSchema,
81
- scalars: scalarsEnumsHash,
82
- //cache,
83
- cache,
84
- fetchOptions: {
85
- fetcher: queryFetcher,
86
- subscriber: subscriptionsClient,
87
- },
88
- });
89
- /*const client: GQtyClient<GeneratedSchema> = createClient<GeneratedSchema>({
90
- schema: generatedSchema,
91
- scalarsEnumsHash,
92
- queryFetcher,
93
- subscriptionsClient,
94
- normalization: args?.normalization === true,
95
- defaults: {
96
- resolved: {
97
- noCache: args?.cache !== true,
98
- retry: false,
99
- },
100
- },
101
- ...args,
102
- });*/
103
- return { subscriptionsClient, client };
104
- }
@@ -1,6 +0,0 @@
1
- import type { ExecutionResult } from 'graphql';
2
- export declare const defaultResponseHandler: (response: Response) => Promise<ExecutionResult<import("graphql/jsutils/ObjMap").ObjMap<unknown>, import("graphql/jsutils/ObjMap").ObjMap<unknown>>>;
3
- export declare const parseResponse: (response: Response) => Promise<any>;
4
- export declare function assertExecutionResult(input: unknown): asserts input is ExecutionResult;
5
- export declare const isExecutionResult: (input: unknown) => input is ExecutionResult;
6
- export declare const handleResponseErrors: (result: ExecutionResult) => void;
@@ -1,40 +0,0 @@
1
- import { GQtyError } from 'gqty';
2
- export const defaultResponseHandler = async (response) => {
3
- const result = await parseResponse(response);
4
- assertExecutionResult(result);
5
- handleResponseErrors(result);
6
- return result;
7
- };
8
- export const parseResponse = async (response) => {
9
- const text = await response.text().then((text) => text.trim() || null);
10
- if (response.status >= 400) {
11
- throw new GQtyError(`Received HTTP ${response.status} from GraphQL endpoint${text
12
- ? `, body: ${text.length > 50 ? `${text.slice(0, 50)}...` : text}`
13
- : ''}.`);
14
- }
15
- if (!text) {
16
- throw new GQtyError('Received an empty response from GraphQL endpoint.');
17
- }
18
- try {
19
- return JSON.parse(text);
20
- }
21
- catch (error) {
22
- throw new GQtyError(`Received malformed JSON response from GraphQL endpoint: ${text.length > 50 ? `${text.slice(0, 50)}...` : text}`);
23
- }
24
- };
25
- export function assertExecutionResult(input) {
26
- if (!isExecutionResult(input)) {
27
- throw new GQtyError(`Expected response to be an ExecutionResult, received: ${JSON.stringify(input)}`);
28
- }
29
- }
30
- export const isExecutionResult = (input) => {
31
- if (typeof input !== 'object' || input === null)
32
- return false;
33
- const value = input;
34
- return 'data' in value || Array.isArray(value.errors);
35
- };
36
- export const handleResponseErrors = (result) => {
37
- if (result.errors?.length) {
38
- throw GQtyError.fromGraphQLErrors(result.errors);
39
- }
40
- };
@@ -1,120 +0,0 @@
1
- // import fetch from 'cross-fetch';
2
- import { Cache, type QueryFetcher, createClient } from 'gqty';
3
- import { createClient as createSubscriptionsClient } from 'graphql-ws';
4
- import { hasuraGraphqlUri, hasuraQueryTypeHeader } from './constants';
5
- import {
6
- type GeneratedSchema,
7
- generatedSchema,
8
- scalarsEnumsHash,
9
- } from './gqty';
10
- import { defaultResponseHandler } from './gqty/error';
11
- import type { GqlAuthParam, Headers } from './types';
12
-
13
- export function useHasuraClientInner(args?: Omit<GqlAuthParam, 'retries'>) {
14
- const $headers = args && 'headers' in args ? args.headers : undefined;
15
- const $fetch = (args && 'fetch' in args ? args.fetch : undefined) || fetch;
16
- const uri = args?.uri || hasuraGraphqlUri;
17
-
18
- const getHeaders = async (base?: Headers): Promise<Headers> => {
19
- const headers: Record<string, any> =
20
- ($headers && typeof $headers === 'function'
21
- ? await $headers()
22
- : $headers) || {};
23
- if (base) for (const key in base) headers[key] = base[key];
24
- if (args && 'secret' in args && args.secret) {
25
- headers['x-hasura-admin-secret'] = args.secret;
26
- } else if (args && 'accessToken' in args && args.accessToken) {
27
- headers.authorization = args.accessToken.startsWith('Bearer ')
28
- ? args.accessToken
29
- : `Bearer ${args.accessToken}`;
30
- }
31
- if (args?.auditUserId) headers['x-hasura-audit-user-id'] = args.auditUserId;
32
- return headers;
33
- };
34
-
35
- const queryFetcher: QueryFetcher = async (
36
- { query, variables, operationName },
37
- fetchOptions
38
- ) => {
39
- const headers = await getHeaders();
40
- if (fetchOptions?.headers) {
41
- for (const key in fetchOptions.headers) {
42
- headers[key] = fetchOptions.headers[key];
43
- }
44
- }
45
-
46
- // Modify "https://finalytic.hasura.app/v1/graphql" if needed
47
- const response = await $fetch('https://finalytic.hasura.app/v1/graphql', {
48
- ...fetchOptions,
49
- method: 'POST',
50
- headers: {
51
- 'Content-Type': 'application/json',
52
- ...headers,
53
- },
54
- body: JSON.stringify({
55
- query,
56
- variables,
57
- operationName,
58
- }),
59
- mode: 'cors',
60
- });
61
-
62
- const res = await defaultResponseHandler(response);
63
- return res;
64
- };
65
-
66
- const subscriptionsClient =
67
- args?.subscriptions === true
68
- ? createSubscriptionsClient({
69
- lazy: true,
70
- connectionParams: async () => ({
71
- headers: await getHeaders({
72
- [hasuraQueryTypeHeader]: 'subscription',
73
- }),
74
- }),
75
- url() {
76
- const wsUrl = new URL(uri);
77
- wsUrl.protocol = wsUrl.protocol
78
- .replace('https', 'wss')
79
- .replace('http', 'ws');
80
- return wsUrl.href;
81
- },
82
- /*url: () => {
83
- },*/
84
- })
85
- : undefined;
86
-
87
- const cache = new Cache(undefined, {
88
- maxAge: 0,
89
- staleWhileRevalidate: 0,
90
- normalization: false,
91
- });
92
-
93
- const client = createClient<GeneratedSchema>({
94
- schema: generatedSchema,
95
- scalars: scalarsEnumsHash,
96
- //cache,
97
- cache,
98
- fetchOptions: {
99
- fetcher: queryFetcher,
100
- subscriber: subscriptionsClient,
101
- },
102
- });
103
-
104
- /*const client: GQtyClient<GeneratedSchema> = createClient<GeneratedSchema>({
105
- schema: generatedSchema,
106
- scalarsEnumsHash,
107
- queryFetcher,
108
- subscriptionsClient,
109
- normalization: args?.normalization === true,
110
- defaults: {
111
- resolved: {
112
- noCache: args?.cache !== true,
113
- retry: false,
114
- },
115
- },
116
- ...args,
117
- });*/
118
-
119
- return { subscriptionsClient, client };
120
- }