nuxt-graphql-middleware 4.1.1 → 4.3.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.
Files changed (63) hide show
  1. package/dist/client/200.html +9 -9
  2. package/dist/client/404.html +9 -9
  3. package/dist/client/_nuxt/{Bk31qVW4.js → B4FhP7a6.js} +1 -1
  4. package/dist/client/_nuxt/CH4m2wxh.js +25 -0
  5. package/dist/client/_nuxt/CPd6XBwJ.js +1 -0
  6. package/dist/client/_nuxt/GKcsigNx.js +1 -0
  7. package/dist/client/_nuxt/VR7nYXIq.js +2 -0
  8. package/dist/client/_nuxt/builds/latest.json +1 -1
  9. package/dist/client/_nuxt/builds/meta/172a2fbf-9aed-4d11-81c4-ac46ab9b664c.json +1 -0
  10. package/dist/client/_nuxt/entry.D9ltLgme.css +1 -0
  11. package/dist/client/_nuxt/error-404.SWzu_puR.css +1 -0
  12. package/dist/client/_nuxt/error-500.Bkv_zTjr.css +1 -0
  13. package/dist/client/index.html +9 -9
  14. package/dist/module.d.mts +21 -17
  15. package/dist/module.d.ts +21 -17
  16. package/dist/module.json +3 -3
  17. package/dist/module.mjs +177 -73
  18. package/dist/runtime/clientOptions/index.d.ts +2 -0
  19. package/dist/runtime/clientOptions/index.js +3 -0
  20. package/dist/runtime/composables/nuxtApp.js +1 -1
  21. package/dist/runtime/composables/useAsyncGraphqlQuery.d.ts +4 -2
  22. package/dist/runtime/composables/useAsyncGraphqlQuery.js +26 -10
  23. package/dist/runtime/composables/useGraphqlMutation.d.ts +2 -2
  24. package/dist/runtime/composables/useGraphqlMutation.js +19 -2
  25. package/dist/runtime/composables/useGraphqlQuery.d.ts +2 -2
  26. package/dist/runtime/composables/useGraphqlQuery.js +29 -4
  27. package/dist/runtime/composables/useGraphqlState.d.ts +2 -1
  28. package/dist/runtime/composables/useGraphqlUploadMutation.d.ts +2 -2
  29. package/dist/runtime/composables/useGraphqlUploadMutation.js +19 -3
  30. package/dist/runtime/{composables/shared.d.ts → helpers/composables.d.ts} +8 -1
  31. package/dist/runtime/helpers/composables.js +17 -0
  32. package/dist/runtime/plugins/provideState.d.ts +6 -1
  33. package/dist/runtime/server/tsconfig.json +3 -0
  34. package/dist/runtime/server/utils/index.d.ts +3 -0
  35. package/dist/runtime/server/utils/index.js +12 -0
  36. package/dist/runtime/server/utils/useGraphqlMutation.d.ts +7 -0
  37. package/dist/runtime/server/utils/useGraphqlMutation.js +20 -0
  38. package/dist/runtime/server/utils/useGraphqlQuery.d.ts +7 -0
  39. package/dist/runtime/server/utils/useGraphqlQuery.js +21 -0
  40. package/dist/runtime/serverHandler/helpers/index.d.ts +10 -6
  41. package/dist/runtime/serverHandler/helpers/index.js +40 -9
  42. package/dist/runtime/serverHandler/index.js +15 -7
  43. package/dist/runtime/serverHandler/tsconfig.json +3 -0
  44. package/dist/runtime/serverHandler/upload.js +16 -8
  45. package/dist/runtime/serverOptions/defineGraphqlServerOptions.d.ts +2 -1
  46. package/dist/runtime/settings/index.d.ts +2 -1
  47. package/dist/runtime/settings/index.js +2 -1
  48. package/dist/runtime/types.d.ts +52 -1
  49. package/dist/types.d.mts +0 -4
  50. package/dist/types.d.ts +0 -4
  51. package/package.json +15 -8
  52. package/dist/client/_nuxt/CHM3Rz8p.js +0 -1
  53. package/dist/client/_nuxt/CUKk0hSk.js +0 -24
  54. package/dist/client/_nuxt/Ca6k-hEN.js +0 -2
  55. package/dist/client/_nuxt/KmIjpfWJ.js +0 -1
  56. package/dist/client/_nuxt/builds/meta/42e92f16-7f29-4b6f-8e46-68076031ade3.json +0 -1
  57. package/dist/client/_nuxt/entry.BMcZ91J5.css +0 -1
  58. package/dist/client/_nuxt/error-404.CjTTbIxB.css +0 -1
  59. package/dist/client/_nuxt/error-500.B4KzowuE.css +0 -1
  60. package/dist/runtime/composables/server.d.ts +0 -11
  61. package/dist/runtime/composables/server.js +0 -29
  62. package/dist/runtime/composables/shared.js +0 -5
  63. /package/dist/client/_nuxt/{index.DCCKx2Zk.css → index.D19Q16VT.css} +0 -0
@@ -1,11 +1,13 @@
1
1
  import type { FetchOptions } from 'ofetch';
2
- import type { GraphqlMiddlewareQuery, GraphqlMiddlewareMutation } from '#build/nuxt-graphql-middleware';
2
+ import type { GraphqlMiddlewareQuery, GraphqlMiddlewareMutation } from '#nuxt-graphql-middleware/generated-types';
3
3
  import type { RequestCacheOptions } from '#graphql-middleware/types';
4
+ import type { GraphqlClientContext } from '#graphql-middleware-client-options';
4
5
  export type GraphqlMiddlewareQueryName = keyof GraphqlMiddlewareQuery;
5
6
  export type GraphqlMiddlewareMutationName = keyof GraphqlMiddlewareMutation;
6
7
  export type GraphqlComposableOptions = {
7
8
  fetchOptions?: FetchOptions;
8
9
  graphqlCaching?: RequestCacheOptions;
10
+ clientContext?: Partial<GraphqlClientContext>;
9
11
  };
10
12
  export type GetQueryArgs<T extends GraphqlMiddlewareQueryName, M extends GraphqlMiddlewareQuery> = M[T][0] extends null ? [T, (null | undefined)?, GraphqlComposableOptions?] : M[T][1] extends false ? [T, M[T][0], GraphqlComposableOptions?] : [T, M[T][0]?, GraphqlComposableOptions?];
11
13
  export type GetMutationArgs<T extends GraphqlMiddlewareMutationName, M extends GraphqlMiddlewareMutation> = M[T][0] extends null ? [T, (null | undefined)?, GraphqlComposableOptions?] : M[T][1] extends false ? [T, M[T][0], GraphqlComposableOptions?] : [T, M[T][0]?, GraphqlComposableOptions?];
@@ -16,21 +18,26 @@ export type QueryObjectArgs<T extends GraphqlMiddlewareQueryName, M extends Grap
16
18
  name: T;
17
19
  fetchOptions?: FetchOptions;
18
20
  graphqlCaching?: RequestCacheOptions;
21
+ clientContext?: Partial<GraphqlClientContext>;
19
22
  variables?: null;
20
23
  } : {
21
24
  name: T;
22
25
  variables: M[T][0];
23
26
  fetchOptions?: FetchOptions;
24
27
  graphqlCaching?: RequestCacheOptions;
28
+ clientContext?: Partial<GraphqlClientContext>;
25
29
  };
26
30
  export type MutationObjectArgs<T extends GraphqlMiddlewareMutationName, M extends GraphqlMiddlewareMutation> = M[T][0] extends null ? {
27
31
  name: T;
28
32
  variables?: null;
29
33
  fetchOptions?: FetchOptions;
34
+ clientContext?: Partial<GraphqlClientContext>;
30
35
  } : {
31
36
  name: T;
32
37
  variables: M[T][0];
33
38
  fetchOptions?: FetchOptions;
39
+ clientContext?: Partial<GraphqlClientContext>;
34
40
  };
35
41
  export type PickFrom<T, K extends Array<string>> = T extends Array<any> ? T : T extends Record<string, any> ? keyof T extends K[number] ? T : K[number] extends never ? T : Pick<T, K[number]> : T;
36
42
  export type KeysOf<T> = Array<T extends T ? (keyof T extends string ? keyof T : never) : never>;
43
+ export declare function encodeContext(context: Record<string, string | null | undefined>): Record<string, string>;
@@ -0,0 +1,17 @@
1
+ import { useRuntimeConfig } from "#imports";
2
+ import { CLIENT_CONTEXT_PREFIX } from "../settings/index.js";
3
+ export function getEndpoint(operation, operationName) {
4
+ const config = useRuntimeConfig();
5
+ return `${config?.public?.["nuxt-graphql-middleware"]?.serverApiPrefix}/${operation}/${operationName}`;
6
+ }
7
+ export function encodeContext(context) {
8
+ return Object.entries(context).reduce(
9
+ (acc, [key, value]) => {
10
+ if (typeof value === "string") {
11
+ acc[CLIENT_CONTEXT_PREFIX + key] = value;
12
+ }
13
+ return acc;
14
+ },
15
+ {}
16
+ );
17
+ }
@@ -1,5 +1,10 @@
1
+ import { type GraphqlMiddlewareState } from '#graphql-middleware/types';
1
2
  /**
2
3
  * Create and provide the state singleton for the composables.
3
4
  */
4
- declare const _default: any;
5
+ declare const _default: import("#app").Plugin<{
6
+ graphqlState: GraphqlMiddlewareState;
7
+ }> & import("#app").ObjectPlugin<{
8
+ graphqlState: GraphqlMiddlewareState;
9
+ }>;
5
10
  export default _default;
@@ -0,0 +1,3 @@
1
+ {
2
+ "extends": "../../../.nuxt/tsconfig.server.json"
3
+ }
@@ -0,0 +1,3 @@
1
+ import type { FetchOptions } from 'ofetch';
2
+ import type { GraphqlResponse } from '#graphql-middleware-server-options-build';
3
+ export declare function performRequest<T>(operation: string, operationName: string, method: 'get' | 'post', options: FetchOptions): Promise<GraphqlResponse<T>>;
@@ -0,0 +1,12 @@
1
+ import { getEndpoint } from "./../../helpers/composables.js";
2
+ export function performRequest(operation, operationName, method, options) {
3
+ return $fetch(getEndpoint(operation, operationName), {
4
+ ...options,
5
+ method
6
+ }).then((v) => {
7
+ return {
8
+ data: v.data,
9
+ errors: v.errors || []
10
+ };
11
+ });
12
+ }
@@ -0,0 +1,7 @@
1
+ import type { GraphqlResponse } from '#graphql-middleware-server-options-build';
2
+ import { type GraphqlMiddlewareMutationName, type GetMutationArgs, type MutationObjectArgs, type GetMutationResult } from './../../helpers/composables.js';
3
+ import type { GraphqlMiddlewareMutation } from '#nuxt-graphql-middleware/generated-types';
4
+ /**
5
+ * Performs a GraphQL mutation.
6
+ */
7
+ export declare function useGraphqlMutation<T extends GraphqlMiddlewareMutationName, R extends GetMutationResult<T, GraphqlMiddlewareMutation>>(...args: GetMutationArgs<T, GraphqlMiddlewareMutation> | [MutationObjectArgs<T, GraphqlMiddlewareMutation>]): Promise<GraphqlResponse<R>>;
@@ -0,0 +1,20 @@
1
+ import {
2
+ encodeContext
3
+ } from "./../../helpers/composables.js";
4
+ import { performRequest } from "./index.js";
5
+ export function useGraphqlMutation(...args) {
6
+ const [name, body, fetchOptions = {}, clientContext = {}] = typeof args[0] === "string" ? [args[0], args[1], args[2]?.fetchOptions, args[2]?.clientContext] : [
7
+ args[0].name,
8
+ args[0].variables,
9
+ args[0].fetchOptions,
10
+ args[0].clientContext
11
+ ];
12
+ return performRequest("mutation", name, "post", {
13
+ ...fetchOptions,
14
+ body,
15
+ params: {
16
+ ...encodeContext(clientContext),
17
+ ...fetchOptions.params || {}
18
+ }
19
+ });
20
+ }
@@ -0,0 +1,7 @@
1
+ import type { GraphqlResponse } from '#graphql-middleware-server-options-build';
2
+ import { type GraphqlMiddlewareQueryName, type GetQueryArgs, type QueryObjectArgs, type GetQueryResult } from './../../helpers/composables.js';
3
+ import type { GraphqlMiddlewareQuery } from '#nuxt-graphql-middleware/generated-types';
4
+ /**
5
+ * Performs a GraphQL query.
6
+ */
7
+ export declare function useGraphqlQuery<T extends GraphqlMiddlewareQueryName, R extends GetQueryResult<T, GraphqlMiddlewareQuery>>(...args: GetQueryArgs<T, GraphqlMiddlewareQuery> | [QueryObjectArgs<T, GraphqlMiddlewareQuery>]): Promise<GraphqlResponse<R>>;
@@ -0,0 +1,21 @@
1
+ import {
2
+ encodeContext
3
+ } from "./../../helpers/composables.js";
4
+ import { buildRequestParams } from "./../../helpers/index.js";
5
+ import { performRequest } from "./index.js";
6
+ export function useGraphqlQuery(...args) {
7
+ const [name, variables, fetchOptions = {}, clientContext = {}] = typeof args[0] === "string" ? [args[0], args[1], args[2]?.fetchOptions, args[2]?.clientContext] : [
8
+ args[0].name,
9
+ args[0].variables,
10
+ args[0].fetchOptions,
11
+ args[0].clientContext
12
+ ];
13
+ return performRequest("query", name, "get", {
14
+ ...fetchOptions,
15
+ params: {
16
+ ...fetchOptions.params || {},
17
+ ...buildRequestParams(variables),
18
+ ...encodeContext(clientContext)
19
+ }
20
+ });
21
+ }
@@ -1,18 +1,22 @@
1
1
  import { type QueryObject } from 'ufo';
2
2
  import type { H3Event } from 'h3';
3
3
  import type { FetchOptions, FetchResponse, FetchError } from 'ofetch';
4
- import type { GraphqlMiddlewareRuntimeConfig, GraphqlMiddlewareServerOptions } from './../../../types.js';
5
- import { GraphqlMiddlewareOperation } from './../../settings.js';
4
+ import type { GraphqlMiddlewareRequestContext, GraphqlMiddlewareRuntimeConfig, GraphqlMiddlewareServerOptions } from './../../../types.js';
5
+ import { GraphqlMiddlewareOperation } from './../../settings/index.js';
6
6
  import { type Documents } from '#graphql-documents';
7
7
  export declare function queryParamToVariables(query: QueryObject): any;
8
+ /**
9
+ * Extract the client context from the query params.
10
+ */
11
+ export declare function extractRequestContext(query: QueryObject): GraphqlMiddlewareRequestContext<any>;
8
12
  /**
9
13
  * Get the URL of the GraphQL endpoint.
10
14
  */
11
- export declare function getEndpoint(config: GraphqlMiddlewareRuntimeConfig, serverOptions: GraphqlMiddlewareServerOptions, event: H3Event, operation: GraphqlMiddlewareOperation, operationName: string): string | Promise<string>;
15
+ export declare function getEndpoint(config: GraphqlMiddlewareRuntimeConfig, serverOptions: GraphqlMiddlewareServerOptions<any, any>, event: H3Event, operation: GraphqlMiddlewareOperation, operationName: string, context: GraphqlMiddlewareRequestContext<any>): string | Promise<string>;
12
16
  /**
13
17
  * Get the options for the $fetch request to the GraphQL server.
14
18
  */
15
- export declare function getFetchOptions(serverOptions: GraphqlMiddlewareServerOptions, event: H3Event, operation: GraphqlMiddlewareOperation, operationName: string): FetchOptions | Promise<FetchOptions>;
19
+ export declare function getFetchOptions(serverOptions: GraphqlMiddlewareServerOptions<any, any>, event: H3Event, operation: GraphqlMiddlewareOperation, operationName: string, context: GraphqlMiddlewareRequestContext<any>): FetchOptions | Promise<FetchOptions>;
16
20
  export declare function throwError(statusMessage: string, statusCode?: number): never;
17
21
  /**
18
22
  * Assure that the request is valid.
@@ -21,8 +25,8 @@ export declare function validateRequest(method?: string, operation?: GraphqlMidd
21
25
  /**
22
26
  * Handle GraphQL server response.
23
27
  */
24
- export declare function onServerResponse(serverOptions: GraphqlMiddlewareServerOptions, event: H3Event, response: FetchResponse<any>, operation?: string, operationName?: string): any;
28
+ export declare function onServerResponse(serverOptions: GraphqlMiddlewareServerOptions<any, any>, event: H3Event, response: FetchResponse<any>, operation: string, operationName: string, context: GraphqlMiddlewareRequestContext<any>): any;
25
29
  /**
26
30
  * Handle GraphQL server errors.
27
31
  */
28
- export declare function onServerError(serverOptions: GraphqlMiddlewareServerOptions, event: H3Event, error: FetchError, operation?: string, operationName?: string): any;
32
+ export declare function onServerError(serverOptions: GraphqlMiddlewareServerOptions<any, any>, event: H3Event, error: FetchError, operation: string, operationName: string, context: GraphqlMiddlewareRequestContext<any>): any;
@@ -1,5 +1,8 @@
1
1
  import { createError } from "h3";
2
- import { GraphqlMiddlewareOperation } from "./../../settings/index.js";
2
+ import {
3
+ CLIENT_CONTEXT_PREFIX,
4
+ GraphqlMiddlewareOperation
5
+ } from "./../../settings/index.js";
3
6
  export function queryParamToVariables(query) {
4
7
  try {
5
8
  if (query.__variables && typeof query.__variables === "string") {
@@ -9,12 +12,28 @@ export function queryParamToVariables(query) {
9
12
  }
10
13
  return query;
11
14
  }
12
- export function getEndpoint(config, serverOptions, event, operation, operationName) {
15
+ export function extractRequestContext(query) {
16
+ const client = {};
17
+ for (const property in query) {
18
+ if (property.startsWith(CLIENT_CONTEXT_PREFIX)) {
19
+ const value = query[property];
20
+ if (typeof value === "string") {
21
+ const key = property.replace(CLIENT_CONTEXT_PREFIX, "");
22
+ client[key] = value;
23
+ }
24
+ }
25
+ }
26
+ return {
27
+ client
28
+ };
29
+ }
30
+ export function getEndpoint(config, serverOptions, event, operation, operationName, context) {
13
31
  if (serverOptions.graphqlEndpoint) {
14
32
  const result = serverOptions.graphqlEndpoint(
15
33
  event,
16
34
  operation,
17
- operationName
35
+ operationName,
36
+ context
18
37
  );
19
38
  if (result) {
20
39
  return Promise.resolve(result);
@@ -25,9 +44,14 @@ export function getEndpoint(config, serverOptions, event, operation, operationNa
25
44
  }
26
45
  throw new Error("Failed to determine endpoint for GraphQL server.");
27
46
  }
28
- export function getFetchOptions(serverOptions, event, operation, operationName) {
47
+ export function getFetchOptions(serverOptions, event, operation, operationName, context) {
29
48
  if (serverOptions.serverFetchOptions) {
30
- return serverOptions.serverFetchOptions(event, operation, operationName) || {};
49
+ return serverOptions.serverFetchOptions(
50
+ event,
51
+ operation,
52
+ operationName,
53
+ context
54
+ ) || {};
31
55
  }
32
56
  return {};
33
57
  }
@@ -60,20 +84,27 @@ export function validateRequest(method, operation, name, documents) {
60
84
  throwError(`Operation "${operation}" with name "${name}" not found.`);
61
85
  }
62
86
  }
63
- export function onServerResponse(serverOptions, event, response, operation, operationName) {
87
+ export function onServerResponse(serverOptions, event, response, operation, operationName, context) {
64
88
  if (serverOptions.onServerResponse) {
65
89
  return serverOptions.onServerResponse(
66
90
  event,
67
91
  response,
68
92
  operation,
69
- operationName
93
+ operationName,
94
+ context
70
95
  );
71
96
  }
72
97
  return response._data;
73
98
  }
74
- export function onServerError(serverOptions, event, error, operation, operationName) {
99
+ export function onServerError(serverOptions, event, error, operation, operationName, context) {
75
100
  if (serverOptions.onServerError) {
76
- return serverOptions.onServerError(event, error, operation, operationName);
101
+ return serverOptions.onServerError(
102
+ event,
103
+ error,
104
+ operation,
105
+ operationName,
106
+ context
107
+ );
77
108
  }
78
109
  const message = error && "message" in error ? error.message : "";
79
110
  throw createError({
@@ -5,7 +5,8 @@ import {
5
5
  getFetchOptions,
6
6
  validateRequest,
7
7
  onServerResponse,
8
- onServerError
8
+ onServerError,
9
+ extractRequestContext
9
10
  } from "./helpers/index.js";
10
11
  import { GraphqlMiddlewareOperation } from "./../settings/index.js";
11
12
  import { documents } from "#graphql-documents";
@@ -17,14 +18,17 @@ export default defineEventHandler(async (event) => {
17
18
  const operationName = event.context?.params?.name;
18
19
  validateRequest(method, operation, operationName, documents);
19
20
  const operationDocument = documents[operation][operationName];
20
- const variables = operation === GraphqlMiddlewareOperation.Query ? queryParamToVariables(getQuery(event)) : await readBody(event);
21
+ const queryParams = getQuery(event);
22
+ const context = extractRequestContext(queryParams);
23
+ const variables = operation === GraphqlMiddlewareOperation.Query ? queryParamToVariables(queryParams) : await readBody(event);
21
24
  if (serverOptions.doGraphqlRequest) {
22
25
  return serverOptions.doGraphqlRequest({
23
26
  event,
24
27
  operation,
25
28
  operationName,
26
29
  operationDocument,
27
- variables
30
+ variables,
31
+ context
28
32
  });
29
33
  }
30
34
  const runtimeConfig = useRuntimeConfig().graphqlMiddleware;
@@ -33,13 +37,15 @@ export default defineEventHandler(async (event) => {
33
37
  serverOptions,
34
38
  event,
35
39
  operation,
36
- operationName
40
+ operationName,
41
+ context
37
42
  );
38
43
  const fetchOptions = await getFetchOptions(
39
44
  serverOptions,
40
45
  event,
41
46
  operation,
42
- operationName
47
+ operationName,
48
+ context
43
49
  );
44
50
  return $fetch.raw(endpoint, {
45
51
  // @todo: Remove any once https://github.com/unjs/nitro/pull/883 is released.
@@ -56,7 +62,8 @@ export default defineEventHandler(async (event) => {
56
62
  event,
57
63
  response,
58
64
  operation,
59
- operationName
65
+ operationName,
66
+ context
60
67
  );
61
68
  }).catch((error) => {
62
69
  return onServerError(
@@ -64,7 +71,8 @@ export default defineEventHandler(async (event) => {
64
71
  event,
65
72
  error,
66
73
  operation,
67
- operationName
74
+ operationName,
75
+ context
68
76
  );
69
77
  });
70
78
  });
@@ -0,0 +1,3 @@
1
+ {
2
+ "extends": "../../../.nuxt/tsconfig.server.json"
3
+ }
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  defineEventHandler,
3
- readMultipartFormData
3
+ readMultipartFormData,
4
+ getQuery
4
5
  } from "h3";
5
6
  import {
6
7
  getEndpoint,
@@ -8,7 +9,8 @@ import {
8
9
  validateRequest,
9
10
  onServerResponse,
10
11
  onServerError,
11
- throwError
12
+ throwError,
13
+ extractRequestContext
12
14
  } from "./helpers/index.js";
13
15
  import { GraphqlMiddlewareOperation } from "./../settings/index.js";
14
16
  import { documents } from "#graphql-documents";
@@ -52,6 +54,8 @@ export default defineEventHandler(async (event) => {
52
54
  const blob = new Blob([file.data]);
53
55
  formData.append(file.name, blob, file.filename);
54
56
  }
57
+ const queryParams = getQuery(event);
58
+ const context = extractRequestContext(queryParams);
55
59
  if (serverOptions.doGraphqlRequest) {
56
60
  return serverOptions.doGraphqlRequest({
57
61
  event,
@@ -59,7 +63,8 @@ export default defineEventHandler(async (event) => {
59
63
  operationName,
60
64
  operationDocument,
61
65
  variables,
62
- formData
66
+ formData,
67
+ context
63
68
  });
64
69
  }
65
70
  const runtimeConfig = useRuntimeConfig().graphqlMiddleware;
@@ -68,17 +73,18 @@ export default defineEventHandler(async (event) => {
68
73
  serverOptions,
69
74
  event,
70
75
  operation,
71
- operationName
76
+ operationName,
77
+ context
72
78
  );
73
79
  const fetchOptions = await getFetchOptions(
74
80
  serverOptions,
75
81
  event,
76
82
  operation,
77
- operationName
83
+ operationName,
84
+ context
78
85
  );
79
86
  return $fetch.raw(endpoint, {
80
87
  ...fetchOptions,
81
- // @todo: Remove any once https://github.com/unjs/nitro/pull/883 is released.
82
88
  method: "POST",
83
89
  body: formData
84
90
  }).then((response) => {
@@ -87,7 +93,8 @@ export default defineEventHandler(async (event) => {
87
93
  event,
88
94
  response,
89
95
  operation,
90
- operationName
96
+ operationName,
97
+ context
91
98
  );
92
99
  }).catch((error) => {
93
100
  return onServerError(
@@ -95,7 +102,8 @@ export default defineEventHandler(async (event) => {
95
102
  event,
96
103
  error,
97
104
  operation,
98
- operationName
105
+ operationName,
106
+ context
99
107
  );
100
108
  });
101
109
  });
@@ -1,2 +1,3 @@
1
+ import type { GraphqlClientContext } from '#graphql-middleware-client-options';
1
2
  import { type GraphqlMiddlewareServerOptions } from './../../types.js';
2
- export declare function defineGraphqlServerOptions<T extends object>(options: GraphqlMiddlewareServerOptions<T>): GraphqlMiddlewareServerOptions<T>;
3
+ export declare function defineGraphqlServerOptions<T extends object>(options: GraphqlMiddlewareServerOptions<T, GraphqlClientContext>): GraphqlMiddlewareServerOptions<T, GraphqlClientContext>;
@@ -6,7 +6,7 @@ export declare enum GraphqlMiddlewareTemplate {
6
6
  /**
7
7
  * Signature for the GraphQL composable arguments and return types.
8
8
  */
9
- ComposableContext = "nuxt-graphql-middleware.d.ts",
9
+ ComposableContext = "nuxt-graphql-middleware/generated-types.d.ts",
10
10
  /**
11
11
  * Exports a single opject containing the compiled queries and mutations.
12
12
  */
@@ -16,3 +16,4 @@ export declare enum GraphqlMiddlewareOperation {
16
16
  Query = "query",
17
17
  Mutation = "mutation"
18
18
  }
19
+ export declare const CLIENT_CONTEXT_PREFIX = "__gqlc_";
@@ -1,6 +1,6 @@
1
1
  export var GraphqlMiddlewareTemplate = /* @__PURE__ */ ((GraphqlMiddlewareTemplate2) => {
2
2
  GraphqlMiddlewareTemplate2["OperationTypes"] = "graphql-operations.d.ts";
3
- GraphqlMiddlewareTemplate2["ComposableContext"] = "nuxt-graphql-middleware.d.ts";
3
+ GraphqlMiddlewareTemplate2["ComposableContext"] = "nuxt-graphql-middleware/generated-types.d.ts";
4
4
  GraphqlMiddlewareTemplate2["Documents"] = "graphql-documents.mjs";
5
5
  return GraphqlMiddlewareTemplate2;
6
6
  })(GraphqlMiddlewareTemplate || {});
@@ -9,3 +9,4 @@ export var GraphqlMiddlewareOperation = /* @__PURE__ */ ((GraphqlMiddlewareOpera
9
9
  GraphqlMiddlewareOperation2["Mutation"] = "mutation";
10
10
  return GraphqlMiddlewareOperation2;
11
11
  })(GraphqlMiddlewareOperation || {});
12
+ export const CLIENT_CONTEXT_PREFIX = "__gqlc_";
@@ -1,6 +1,6 @@
1
1
  import type { FetchOptions, FetchContext } from 'ofetch';
2
2
  import type { GraphqlResponse } from '#graphql-middleware-server-options-build';
3
- import type { GraphqlMiddlewareResponseUnion } from '#build/nuxt-graphql-middleware';
3
+ import type { GraphqlMiddlewareResponseUnion } from '#nuxt-graphql-middleware/generated-types';
4
4
  export type GraphqlResponseErrorLocation = {
5
5
  line: number;
6
6
  column: number;
@@ -22,3 +22,54 @@ export interface GraphqlMiddlewareState {
22
22
  export type RequestCacheOptions = {
23
23
  client?: boolean;
24
24
  };
25
+ export type ContextType = {
26
+ [key: string]: string | null | undefined;
27
+ };
28
+ export type GraphqlClientOptions<T extends ContextType = ContextType> = {
29
+ /**
30
+ * Build the client context for this request.
31
+ *
32
+ * The method should return an object whose properties and values are strings.
33
+ * This object will be encoded as a query param when making the request to
34
+ * the GraphQL middleware. Each property name is prefixed when converted to a
35
+ * query param to prevent collisions.
36
+ *
37
+ * On the server, the context is reassembled and passed to methods in custom
38
+ * server options such as getEndpoint or serverFetchOptions.
39
+ *
40
+ * One use case would be to pass some state of the Nuxt app to your server
41
+ * options such as the current language.
42
+ *
43
+ * @example
44
+ * Define a context.
45
+ *
46
+ * ```typescript
47
+ * export default defineGraphqlClientOptions({
48
+ * buildClientContext() {
49
+ * // Pass the current language as context.
50
+ * const language = useCurrentLanguage()
51
+ * return {
52
+ * language: language.value,
53
+ * }
54
+ * },
55
+ * })
56
+ * ```
57
+ *
58
+ * Now when a GraphQL query is made with useGraphqlQuery the request URL will
59
+ * look like this:
60
+ * `/api/graphql_middleware/myQuery?queryVariable=foo&__gqlc_language=en`
61
+ * ^ your context
62
+ *
63
+ * Then in your serverOptions file, you can then access the context:
64
+ *
65
+ * ```typescript
66
+ * export default defineGraphqlServerOptions({
67
+ * graphqlEndpoint(event, operation, operationName, context) {
68
+ * const language = context?.client?.language || 'en'
69
+ * return `http://backend_server/${language}/graphql`
70
+ * },
71
+ * })
72
+ * ```
73
+ */
74
+ buildClientContext?: () => T;
75
+ };
package/dist/types.d.mts CHANGED
@@ -4,8 +4,4 @@ declare module '@nuxt/schema' {
4
4
  interface NuxtHooks extends ModuleHooks {}
5
5
  }
6
6
 
7
- declare module 'nuxt/schema' {
8
- interface NuxtHooks extends ModuleHooks {}
9
- }
10
-
11
7
  export { type GraphqlMiddlewareServerOptions, type ModuleHooks, type ModuleOptions, default } from './module.js'
package/dist/types.d.ts CHANGED
@@ -4,8 +4,4 @@ declare module '@nuxt/schema' {
4
4
  interface NuxtHooks extends ModuleHooks {}
5
5
  }
6
6
 
7
- declare module 'nuxt/schema' {
8
- interface NuxtHooks extends ModuleHooks {}
9
- }
10
-
11
7
  export { type GraphqlMiddlewareServerOptions, type ModuleHooks, type ModuleOptions, default } from './module'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nuxt-graphql-middleware",
3
- "version": "4.1.1",
3
+ "version": "4.3.0",
4
4
  "description": "Module to perform GraphQL requests as a server middleware.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -22,6 +22,10 @@
22
22
  "./dist/runtime/serverOptions": {
23
23
  "import": "./dist/runtime/serverOptions/index.js",
24
24
  "types": "./dist/runtime/serverOptions/index.d.ts"
25
+ },
26
+ "./dist/runtime/clientOptions": {
27
+ "import": "./dist/runtime/clientOptions/index.js",
28
+ "types": "./dist/runtime/clientOptions/index.d.ts"
25
29
  }
26
30
  },
27
31
  "main": "./dist/module.cjs",
@@ -33,14 +37,16 @@
33
37
  "scripts": {
34
38
  "prepack": "nuxt-module-build build && npm run client:build",
35
39
  "dev": "nuxi dev playground --trace-warnings",
40
+ "dev:layers": "nuxi dev playground-layers --trace-warnings",
36
41
  "debug": "nuxi dev playground --inspect",
37
42
  "dev:build": "nuxi build playground",
38
- "dev:prepare": "nuxt-module-build --stub && nuxi prepare playground",
43
+ "dev:layers:build": "nuxi build playground-layers",
44
+ "dev:prepare": "MODULE_BUILD=true nuxt-module-build build --stub && MODULE_BUILD=true nuxt-module-build prepare && nuxi prepare playground && nuxi prepare playground-layers",
39
45
  "dev:start": "node ./playground/.output/server/index.mjs",
40
46
  "client:build": "nuxi generate client",
41
47
  "client:dev": "nuxi dev client --port 3300",
42
48
  "typedoc": "typedoc --plugin typedoc-plugin-markdown --out foobar",
43
- "typecheck": "nuxi typecheck",
49
+ "typecheck": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit",
44
50
  "docs:dev": "vitepress dev docs --port 5000",
45
51
  "docs:build": "vitepress build docs",
46
52
  "docs:serve": "vitepress serve docs --port 5000",
@@ -73,8 +79,8 @@
73
79
  "@nuxt/devtools": "^1.3.7",
74
80
  "@nuxt/devtools-ui-kit": "1.3.7",
75
81
  "@nuxt/eslint": "^0.3.13",
76
- "@nuxt/module-builder": "^0.8.1",
77
- "@nuxt/schema": "^3.12.2",
82
+ "@nuxt/module-builder": "^0.8.4",
83
+ "@nuxt/schema": "^3.13.2",
78
84
  "@types/capture-console": "^1.0.5",
79
85
  "@types/cli-table": "^0.3.4",
80
86
  "@types/inquirer": "^9.0.7",
@@ -83,12 +89,13 @@
83
89
  "eslint-config-prettier": "^9.1.0",
84
90
  "eslint-plugin-prettier": "^5.1.3",
85
91
  "jsdoc-to-markdown": "^8.0.1",
86
- "nuxt": "^3.12.2",
92
+ "nuxt": "^3.13.2",
87
93
  "prettier": "^3.3.2",
88
94
  "strip-ansi": "^7.1.0",
89
95
  "typedoc": "^0.26.3",
90
96
  "typedoc-plugin-markdown": "^4.1.1",
91
- "vitepress": "^1.2.3",
92
- "vitest": "^1.6.0"
97
+ "vitepress": "^1.5.0",
98
+ "vitest": "^1.6.0",
99
+ "vue-tsc": "^2.1.6"
93
100
  }
94
101
  }
@@ -1 +0,0 @@
1
- import{u as w,d as E,r as S,a as A,o as I,b as T,c as U,e as V,f as D,h as P,g as N,p as H,n as O,w as F,i as b,j as z,k as $,l as M,m as Q,q as G,s as W,_ as J,t as K,v as X,x as _,y as k,z as Y,A as Z,B as ee,C as te,D as ae}from"./CUKk0hSk.js";import{u as ne}from"./Bk31qVW4.js";async function j(t,a=w()){const{path:i,matched:v}=a.resolve(t);if(!v.length||(a._routePreloaded||(a._routePreloaded=new Set),a._routePreloaded.has(i)))return;const e=a._preloadPromises=a._preloadPromises||[];if(e.length>4)return Promise.all(e).then(()=>j(t,a));a._routePreloaded.add(i);const n=v.map(l=>{var r;return(r=l.components)==null?void 0:r.default}).filter(l=>typeof l=="function");for(const l of n){const r=Promise.resolve(l()).catch(()=>{}).finally(()=>e.splice(e.indexOf(r)));e.push(r)}await Promise.all(e)}const re=(...t)=>t.find(a=>a!==void 0);function oe(t){const a=t.componentName||"NuxtLink";function i(e,n){if(!e||t.trailingSlash!=="append"&&t.trailingSlash!=="remove")return e;if(typeof e=="string")return R(e,t.trailingSlash);const l="path"in e&&e.path!==void 0?e.path:n(e).path;return{...e,name:void 0,path:R(l,t.trailingSlash)}}function v(e){const n=w(),l=Q(),r=b(()=>!!e.target&&e.target!=="_self"),u=b(()=>{const c=e.to||e.href||"";return typeof c=="string"&&z(c,{acceptRelative:!0})}),m=N("RouterLink"),p=m&&typeof m!="string"?m.useLink:void 0,h=b(()=>{if(e.external)return!0;const c=e.to||e.href||"";return typeof c=="object"?!1:c===""||u.value}),s=b(()=>{const c=e.to||e.href||"";return h.value?c:i(c,n.resolve)}),d=h.value||p==null?void 0:p({...e,to:s}),g=b(()=>{var c;if(!s.value||u.value)return s.value;if(h.value){const f=typeof s.value=="object"?q(s.value):s.value;return i(f,n.resolve)}return typeof s.value=="object"?((c=n.resolve(s.value))==null?void 0:c.href)??null:i($(l.app.baseURL,s.value),n.resolve)});return{to:s,hasTarget:r,isAbsoluteUrl:u,isExternal:h,href:g,isActive:(d==null?void 0:d.isActive)??b(()=>s.value===n.currentRoute.value.path),isExactActive:(d==null?void 0:d.isExactActive)??b(()=>s.value===n.currentRoute.value.path),route:(d==null?void 0:d.route)??b(()=>n.resolve(s.value)),async navigate(){await M(g.value,{replace:e.replace,external:h.value||r.value})}}}return E({name:a,props:{to:{type:[String,Object],default:void 0,required:!1},href:{type:[String,Object],default:void 0,required:!1},target:{type:String,default:void 0,required:!1},rel:{type:String,default:void 0,required:!1},noRel:{type:Boolean,default:void 0,required:!1},prefetch:{type:Boolean,default:void 0,required:!1},noPrefetch:{type:Boolean,default:void 0,required:!1},activeClass:{type:String,default:void 0,required:!1},exactActiveClass:{type:String,default:void 0,required:!1},prefetchedClass:{type:String,default:void 0,required:!1},replace:{type:Boolean,default:void 0,required:!1},ariaCurrentValue:{type:String,default:void 0,required:!1},external:{type:Boolean,default:void 0,required:!1},custom:{type:Boolean,default:void 0,required:!1}},useLink:v,setup(e,{slots:n}){const l=w(),{to:r,href:u,navigate:m,isExternal:p,hasTarget:h,isAbsoluteUrl:s}=v(e),d=S(!1),g=S(null),c=f=>{var x;g.value=e.custom?(x=f==null?void 0:f.$el)==null?void 0:x.nextElementSibling:f==null?void 0:f.$el};if(e.prefetch!==!1&&e.noPrefetch!==!0&&e.target!=="_blank"&&!le()){const x=A();let y,o=null;I(()=>{const L=ie();T(()=>{y=U(()=>{var C;(C=g==null?void 0:g.value)!=null&&C.tagName&&(o=L.observe(g.value,async()=>{o==null||o(),o=null;const B=typeof r.value=="string"?r.value:p.value?q(r.value):l.resolve(r.value).fullPath;await Promise.all([x.hooks.callHook("link:prefetch",B).catch(()=>{}),!p.value&&!h.value&&j(r.value,l).catch(()=>{})]),d.value=!0}))})})}),V(()=>{y&&D(y),o==null||o(),o=null})}return()=>{var y;if(!p.value&&!h.value){const o={ref:c,to:r.value,activeClass:e.activeClass||t.activeClass,exactActiveClass:e.exactActiveClass||t.exactActiveClass,replace:e.replace,ariaCurrentValue:e.ariaCurrentValue,custom:e.custom};return e.custom||(d.value&&(o.class=e.prefetchedClass||t.prefetchedClass),o.rel=e.rel||void 0),P(N("RouterLink"),o,n.default)}const f=e.target||null,x=re(e.noRel?"":e.rel,t.externalRelAttribute,s.value||h.value?"noopener noreferrer":"")||null;return e.custom?n.default?n.default({href:u.value,navigate:m,get route(){if(!u.value)return;const o=new URL(u.value,window.location.href);return{path:o.pathname,fullPath:o.pathname,get query(){return H(o.search)},hash:o.hash,params:{},name:void 0,matched:[],redirectedFrom:void 0,meta:{},href:u.value}},rel:x,target:f,isExternal:p.value||h.value,isActive:!1,isExactActive:!1}):null:P("a",{ref:g,href:u.value||null,rel:x,target:f},(y=n.default)==null?void 0:y.call(n))}}})}const se=oe(O);function R(t,a){const i=a==="append"?G:W;return z(t)&&!t.startsWith("http")?t:i(t,!0)}function ie(){const t=A();if(t._observer)return t._observer;let a=null;const i=new Map,v=(n,l)=>(a||(a=new IntersectionObserver(r=>{for(const u of r){const m=i.get(u.target);(u.isIntersecting||u.intersectionRatio>0)&&m&&m()}})),i.set(n,l),a.observe(n),()=>{i.delete(n),a.unobserve(n),i.size===0&&(a.disconnect(),a=null)});return t._observer={observe:v}}function le(){const t=navigator.connection;return!!(t&&(t.saveData||/2g/.test(t.effectiveType)))}function q(t){return F(t.path||"",t.query||{})+(t.hash?"#"+t.hash:"")}const ue=t=>(te("data-v-c6c1efc1"),t=t(),ae(),t),ce={class:"font-sans antialiased bg-white dark:bg-black text-black dark:text-white grid min-h-screen place-content-center overflow-hidden"},de=ue(()=>_("div",{class:"fixed left-0 right-0 spotlight z-10"},null,-1)),fe={class:"max-w-520px text-center z-20"},he=["textContent"],ve=["textContent"],pe={class:"w-full flex items-center justify-center"},ge={__name:"error-404",props:{appName:{type:String,default:"Nuxt"},version:{type:String,default:""},statusCode:{type:Number,default:404},statusMessage:{type:String,default:"Not Found"},description:{type:String,default:"Sorry, the page you are looking for could not be found."},backHome:{type:String,default:"Go back home"}},setup(t){const a=t;return ne({title:`${a.statusCode} - ${a.statusMessage} | ${a.appName}`,script:[],style:[{children:'*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:var(--un-default-border-color, #e5e7eb)}:before,:after{--un-content:""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}h1{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}h1,p{margin:0}*,:before,:after{--un-rotate:0;--un-rotate-x:0;--un-rotate-y:0;--un-rotate-z:0;--un-scale-x:1;--un-scale-y:1;--un-scale-z:1;--un-skew-x:0;--un-skew-y:0;--un-translate-x:0;--un-translate-y:0;--un-translate-z:0;--un-pan-x: ;--un-pan-y: ;--un-pinch-zoom: ;--un-scroll-snap-strictness:proximity;--un-ordinal: ;--un-slashed-zero: ;--un-numeric-figure: ;--un-numeric-spacing: ;--un-numeric-fraction: ;--un-border-spacing-x:0;--un-border-spacing-y:0;--un-ring-offset-shadow:0 0 rgb(0 0 0 / 0);--un-ring-shadow:0 0 rgb(0 0 0 / 0);--un-shadow-inset: ;--un-shadow:0 0 rgb(0 0 0 / 0);--un-ring-inset: ;--un-ring-offset-width:0px;--un-ring-offset-color:#fff;--un-ring-width:0px;--un-ring-color:rgb(147 197 253 / .5);--un-blur: ;--un-brightness: ;--un-contrast: ;--un-drop-shadow: ;--un-grayscale: ;--un-hue-rotate: ;--un-invert: ;--un-saturate: ;--un-sepia: ;--un-backdrop-blur: ;--un-backdrop-brightness: ;--un-backdrop-contrast: ;--un-backdrop-grayscale: ;--un-backdrop-hue-rotate: ;--un-backdrop-invert: ;--un-backdrop-opacity: ;--un-backdrop-saturate: ;--un-backdrop-sepia: }'}]}),(i,v)=>{const e=se;return K(),X("div",ce,[de,_("div",fe,[_("h1",{class:"text-8xl sm:text-10xl font-medium mb-8",textContent:k(t.statusCode)},null,8,he),_("p",{class:"text-xl px-8 sm:px-0 sm:text-4xl font-light mb-16 leading-tight",textContent:k(t.description)},null,8,ve),_("div",pe,[Y(e,{to:"/",class:"gradient-border text-md sm:text-xl py-2 px-4 sm:py-3 sm:px-6 cursor-pointer"},{default:Z(()=>[ee(k(t.backHome),1)]),_:1})])])])}}},xe=J(ge,[["__scopeId","data-v-c6c1efc1"]]);export{xe as default};