nuxt-graphql-middleware 3.0.0-beta.2 → 3.0.0-beta.4

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.
@@ -1,15 +1,15 @@
1
- import type { Ref } from 'vue';
2
1
  import { GraphqlMiddlewareState } from './../../types';
3
2
  import type { GraphqlMiddlewareQuery, GraphqlMiddlewareMutation } from '#build/nuxt-graphql-middleware';
4
- declare type GraphqlMiddlewareQueryName = keyof GraphqlMiddlewareQuery;
5
- declare type GraphqlMiddlewareMutationName = keyof GraphqlMiddlewareMutation;
6
- declare type GraphqlMiddlewareOperationMap = GraphqlMiddlewareQuery | GraphqlMiddlewareMutation;
7
- declare type GetArgs<T extends GraphqlMiddlewareQueryName, M extends GraphqlMiddlewareOperationMap> = M[T][0] extends null ? [T] : M[T][1] extends false ? [T, M[T][0]] : [T, M[T][0]?];
8
- declare type GraphqlResponse<T> = {
3
+ type GraphqlMiddlewareQueryName = keyof GraphqlMiddlewareQuery;
4
+ type GraphqlMiddlewareMutationName = keyof GraphqlMiddlewareMutation;
5
+ type GetQueryArgs<T extends GraphqlMiddlewareQueryName, M extends GraphqlMiddlewareQuery> = M[T][0] extends null ? [T] : M[T][1] extends false ? [T, M[T][0]] : [T, M[T][0]?];
6
+ type GetMutationArgs<T extends GraphqlMiddlewareMutationName, M extends GraphqlMiddlewareMutation> = M[T][0] extends null ? [T] : M[T][1] extends false ? [T, M[T][0]] : [T, M[T][0]?];
7
+ type GraphqlResponse<T> = {
9
8
  data: T;
10
9
  };
11
- declare type GetResult<T, M> = M[T] extends undefined ? undefined : GraphqlResponse<M[T][2]>;
12
- export declare const useGraphqlState: () => Ref<GraphqlMiddlewareState>;
13
- export declare function useGraphqlQuery<T extends GraphqlMiddlewareQueryName>(...args: GetArgs<T, GraphqlMiddlewareQuery>): Promise<GetResult<T, GraphqlMiddlewareQuery>>;
14
- export declare function useGraphqlMutation<T extends GraphqlMiddlewareMutationName>(...args: GetArgs<T, GraphqlMiddlewareMutation>): Promise<GetResult<T, GraphqlMiddlewareMutation>>;
10
+ type GetQueryResult<T extends GraphqlMiddlewareQueryName, M extends GraphqlMiddlewareQuery> = M[T] extends undefined ? undefined : GraphqlResponse<M[T][2]>;
11
+ type GetMutationResult<T extends GraphqlMiddlewareMutationName, M extends GraphqlMiddlewareMutation> = M[T] extends undefined ? undefined : GraphqlResponse<M[T][2]>;
12
+ export declare const useGraphqlState: () => GraphqlMiddlewareState;
13
+ export declare function useGraphqlQuery<T extends GraphqlMiddlewareQueryName>(...args: GetQueryArgs<T, GraphqlMiddlewareQuery>): Promise<GetQueryResult<T, GraphqlMiddlewareQuery>>;
14
+ export declare function useGraphqlMutation<T extends GraphqlMiddlewareMutationName>(...args: GetMutationArgs<T, GraphqlMiddlewareMutation>): Promise<GetMutationResult<T, GraphqlMiddlewareMutation>>;
15
15
  export {};
@@ -1,36 +1,28 @@
1
- import { useNuxtApp, useRuntimeConfig } from "#imports";
1
+ import { buildRequestParams } from "./../helpers/index.mjs";
2
+ import { useRuntimeConfig } from "#imports";
2
3
  function getEndpoint(operation, operationName) {
3
4
  const config = useRuntimeConfig();
4
5
  return `${config?.public?.["nuxt-graphql-middleware"]?.serverApiPrefix}/${operation}/${operationName}`;
5
6
  }
7
+ const state = {
8
+ fetchOptions: {}
9
+ };
6
10
  export const useGraphqlState = () => {
7
- const nuxtApp = useNuxtApp();
8
- return nuxtApp?._graphql_middleware;
11
+ return state;
9
12
  };
10
13
  export function useGraphqlQuery(...args) {
11
14
  const name = args[0];
12
15
  if (typeof name !== "string") {
13
16
  return Promise.reject(new Error("Invalid query name"));
14
17
  }
15
- const variables = args[1] || {};
16
- let params = {};
17
- const queryFallback = Object.keys(variables).some((key) => {
18
- const valueType = typeof variables[key];
19
- return valueType === "function" || valueType === "object";
20
- });
21
- if (queryFallback) {
22
- params.__variables = JSON.stringify(variables);
23
- } else {
24
- params = variables;
25
- }
26
- const state = useGraphqlState();
18
+ const state2 = useGraphqlState();
27
19
  return $fetch(getEndpoint("query", name), {
28
- params,
29
- ...state.value.fetchOptions
20
+ params: buildRequestParams(args[1]),
21
+ ...state2.fetchOptions
30
22
  });
31
23
  }
32
24
  export function useGraphqlMutation(...args) {
33
- const state = useGraphqlState();
25
+ const state2 = useGraphqlState();
34
26
  const name = args[0];
35
27
  const body = args[1] || {};
36
28
  if (typeof name !== "string") {
@@ -39,6 +31,6 @@ export function useGraphqlMutation(...args) {
39
31
  return $fetch(getEndpoint("mutation", name), {
40
32
  method: "post",
41
33
  body,
42
- ...state.value.fetchOptions
34
+ ...state2.fetchOptions
43
35
  });
44
36
  }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Type check for falsy values.
3
+ *
4
+ * Used as the callback for array.filter, e.g.
5
+ * items.filter(falsy)
6
+ */
7
+ export declare function falsy<T>(value: T): value is NonNullable<T>;
8
+ /**
9
+ * Get the parameters for the GraphQL middleware query.
10
+ */
11
+ export declare function buildRequestParams(variables?: Record<string, any> | undefined | null): Record<string, any>;
@@ -0,0 +1,16 @@
1
+ export function falsy(value) {
2
+ return value !== null && value !== void 0;
3
+ }
4
+ export function buildRequestParams(variables) {
5
+ if (!variables) {
6
+ return {};
7
+ }
8
+ for (const key in variables) {
9
+ if (typeof variables[key] !== "string") {
10
+ return {
11
+ __variables: JSON.stringify(variables)
12
+ };
13
+ }
14
+ }
15
+ return variables;
16
+ }
@@ -0,0 +1,6 @@
1
+ import type { GraphqlMiddlewareConfig } from './../../../types';
2
+ /**
3
+ * Due to nuxt's architecture, we have to manually load the runtime configuration.
4
+ * This is only done for the first time and we cache the config locally.
5
+ */
6
+ export declare function getModuleConfig(): Promise<GraphqlMiddlewareConfig>;
@@ -0,0 +1,15 @@
1
+ import { loadNuxtConfig } from "@nuxt/kit";
2
+ import { useRuntimeConfig } from "#imports";
3
+ let moduleConfig = null;
4
+ export function getModuleConfig() {
5
+ if (moduleConfig) {
6
+ return Promise.resolve(moduleConfig);
7
+ }
8
+ const { graphqlMiddleware } = useRuntimeConfig();
9
+ return loadNuxtConfig({
10
+ cwd: graphqlMiddleware.rootDir
11
+ }).then((v) => {
12
+ moduleConfig = v.graphqlMiddleware;
13
+ return v.graphqlMiddleware;
14
+ });
15
+ }
@@ -1,2 +1,18 @@
1
- export declare function parseQuery(query: Record<string, any>): void;
2
- export declare function parseJSON(object: object): string;
1
+ import { QueryObject } from 'ufo';
2
+ import type { H3Event } from 'h3';
3
+ import type { FetchOptions } from 'ofetch';
4
+ import type { GraphqlMiddlewareConfig } from './../../../types';
5
+ import { GraphqlMiddlewareOperation } from './../../settings';
6
+ export declare function queryParamToVariables(query: QueryObject): any;
7
+ /**
8
+ * Get the URL of the GraphQL endpoint.
9
+ */
10
+ export declare function getEndpoint(moduleConfig: GraphqlMiddlewareConfig, event: H3Event, operation: GraphqlMiddlewareOperation, operationName: string): string;
11
+ /**
12
+ * Get the options for the $fetch request to the GraphQL server.
13
+ */
14
+ export declare function getFetchOptions(moduleConfig: GraphqlMiddlewareConfig, event: H3Event, operation: GraphqlMiddlewareOperation, operationName: string): FetchOptions;
15
+ /**
16
+ * Assure that the request is valid.
17
+ */
18
+ export declare function validateRequest(method?: string, operation?: GraphqlMiddlewareOperation, name?: string, documents?: Record<string, Record<string, string>>): void;
@@ -1,4 +1,63 @@
1
- export function parseQuery(query) {
1
+ import { createError } from "h3";
2
+ import { GraphqlMiddlewareOperation } from "./../../settings/index.mjs";
3
+ export function queryParamToVariables(query) {
4
+ try {
5
+ if (query.__variables && typeof query.__variables === "string") {
6
+ return JSON.parse(query.__variables);
7
+ }
8
+ } catch (_e) {
9
+ }
10
+ return query;
2
11
  }
3
- export function parseJSON(object) {
12
+ export function getEndpoint(moduleConfig, event, operation, operationName) {
13
+ if (typeof moduleConfig.graphqlEndpoint === "string") {
14
+ return moduleConfig.graphqlEndpoint;
15
+ } else if (typeof moduleConfig.graphqlEndpoint === "function") {
16
+ const endpoint = moduleConfig.graphqlEndpoint(
17
+ event,
18
+ operation,
19
+ operationName
20
+ );
21
+ if (endpoint && typeof endpoint === "string") {
22
+ return endpoint;
23
+ }
24
+ }
25
+ throw new Error("Failed to determine endpoint for GraphQL server.");
26
+ }
27
+ export function getFetchOptions(moduleConfig, event, operation, operationName) {
28
+ if (typeof moduleConfig.serverFetchOptions === "function") {
29
+ return moduleConfig.serverFetchOptions(event, operation, operationName) || {};
30
+ } else if (typeof moduleConfig.serverFetchOptions === "object") {
31
+ return moduleConfig.serverFetchOptions;
32
+ }
33
+ return {};
34
+ }
35
+ function throwError(statusMessage, statusCode = 400) {
36
+ throw createError({
37
+ statusCode,
38
+ statusMessage
39
+ });
40
+ }
41
+ export function validateRequest(method, operation, name, documents) {
42
+ if (method !== "POST" && method !== "GET") {
43
+ throwError("Method not allowed.", 405);
44
+ }
45
+ if (operation !== GraphqlMiddlewareOperation.Query && operation !== GraphqlMiddlewareOperation.Mutation) {
46
+ throwError("Unknown operation.");
47
+ }
48
+ if (method === "POST" && operation !== GraphqlMiddlewareOperation.Mutation) {
49
+ throwError("Queries must be a GET request.");
50
+ }
51
+ if (method === "GET" && operation !== GraphqlMiddlewareOperation.Query) {
52
+ throwError("Mutations must be a POST request.");
53
+ }
54
+ if (!name) {
55
+ throwError("Missing name for operation.");
56
+ }
57
+ if (!documents) {
58
+ throwError("Failed to load GraphQL documents", 500);
59
+ }
60
+ if (!documents[operation][name]) {
61
+ throwError(`Operation "${operation}" with name "${name}" not found.`);
62
+ }
4
63
  }
@@ -1,2 +1,2 @@
1
- declare const _default: import("h3").EventHandler<unknown>;
1
+ declare const _default: import("h3").EventHandler<any>;
2
2
  export default _default;
@@ -5,89 +5,45 @@ import {
5
5
  getMethod,
6
6
  readBody
7
7
  } from "h3";
8
- import { loadNuxtConfig } from "@nuxt/kit";
9
- import { useRuntimeConfig } from "#imports";
10
- import operations from "#graphql-documents";
11
- var GraphqlMiddlewareOperation = /* @__PURE__ */ ((GraphqlMiddlewareOperation2) => {
12
- GraphqlMiddlewareOperation2["Query"] = "query";
13
- GraphqlMiddlewareOperation2["Mutation"] = "mutation";
14
- return GraphqlMiddlewareOperation2;
15
- })(GraphqlMiddlewareOperation || {});
16
- let moduleConfig = null;
17
- function getModuleConfig() {
18
- if (moduleConfig) {
19
- return Promise.resolve(moduleConfig);
20
- }
21
- const { graphqlMiddleware } = useRuntimeConfig();
22
- return loadNuxtConfig({
23
- cwd: graphqlMiddleware.rootDir
24
- }).then((v) => {
25
- moduleConfig = v.graphqlMiddleware;
26
- return v.graphqlMiddleware;
27
- });
28
- }
29
- function queryParamToVariables(query) {
30
- try {
31
- if (query.__variables && typeof query.__variables === "string") {
32
- return JSON.parse(query.__variables);
33
- }
34
- } catch (_e) {
35
- }
36
- return query;
37
- }
38
- function getEndpoint(moduleConfig2, event, operation, operationName) {
39
- if (typeof moduleConfig2.graphqlEndpoint === "string") {
40
- return moduleConfig2.graphqlEndpoint;
41
- }
42
- return moduleConfig2.graphqlEndpoint(event, operation, operationName);
43
- }
44
- function getFetchOptions(moduleConfig2, event, operation, operationName) {
45
- if (typeof moduleConfig2.serverFetchOptions === "function") {
46
- return moduleConfig2.serverFetchOptions(event, operation, operationName) || {};
47
- } else if (typeof moduleConfig2.serverFetchOptions === "object") {
48
- return moduleConfig2.serverFetchOptions;
49
- }
50
- return {};
51
- }
8
+ import {
9
+ queryParamToVariables,
10
+ getEndpoint,
11
+ getFetchOptions,
12
+ validateRequest
13
+ } from "./helpers";
14
+ import { getModuleConfig } from "./helpers/getModuleConfig.mjs";
15
+ import { GraphqlMiddlewareOperation } from "./../settings/index.mjs";
16
+ import { documents } from "#graphql-documents";
52
17
  export default defineEventHandler(async (event) => {
53
18
  const method = getMethod(event);
54
19
  const operation = event.context.params.operation;
55
- if (method === "POST" && operation !== "mutation" /* Mutation */) {
56
- throw createError({
57
- statusCode: 400,
58
- statusMessage: "Mutations must be a POST request."
59
- });
60
- }
61
- if (method === "GET" && operation !== "query" /* Query */) {
62
- throw createError({
63
- statusCode: 400,
64
- statusMessage: "Queries must be a GET request."
65
- });
66
- }
67
20
  const name = event.context.params.name;
68
- const query = operations[operation][name];
69
- if (!query) {
70
- throw createError({
71
- statusCode: 400,
72
- statusMessage: `Operation "${operation}" with name "${name} not found."`
73
- });
74
- }
21
+ validateRequest(method, operation, name, documents);
22
+ const query = documents[operation][name];
75
23
  const config = await getModuleConfig();
76
24
  const endpoint = getEndpoint(config, event, operation, name);
77
25
  const fetchOptions = getFetchOptions(config, event, operation, name);
78
- const variables = operation === "query" /* Query */ ? queryParamToVariables(getQuery(event)) : readBody(event);
79
- return $fetch(endpoint, {
26
+ const variables = operation === GraphqlMiddlewareOperation.Query ? queryParamToVariables(getQuery(event)) : await readBody(event);
27
+ return $fetch.raw(endpoint, {
80
28
  method: "POST",
81
29
  body: {
82
30
  query,
83
31
  variables
84
32
  },
85
33
  ...fetchOptions
34
+ }).then((response) => {
35
+ if (config.onServerResponse) {
36
+ return config.onServerResponse(event, response, operation, name);
37
+ }
38
+ return response._data;
86
39
  }).catch((err) => {
40
+ if (config.onServerError) {
41
+ return config.onServerError(event, err, operation, name);
42
+ }
87
43
  throw createError({
88
44
  statusCode: 500,
89
45
  statusMessage: "Couldn't execute GraphQL query.",
90
- data: err && "message" in err ? err.mess : err
46
+ data: err && "message" in err ? err.message : err
91
47
  });
92
48
  });
93
49
  });
@@ -0,0 +1,18 @@
1
+ export declare enum GraphqlMiddlewareTemplate {
2
+ /**
3
+ * Contains the TS definitions for all GraphQL queries, mutations and fragments.
4
+ */
5
+ OperationTypes = "graphql-operations.d.ts",
6
+ /**
7
+ * Signature for the GraphQL composable arguments and return types.
8
+ */
9
+ ComposableContext = "nuxt-graphql-middleware.d.ts",
10
+ /**
11
+ * Exports a single opject containing the compiled queries and mutations.
12
+ */
13
+ Documents = "graphql-documents.mjs"
14
+ }
15
+ export declare enum GraphqlMiddlewareOperation {
16
+ Query = "query",
17
+ Mutation = "mutation"
18
+ }
@@ -0,0 +1,11 @@
1
+ export var GraphqlMiddlewareTemplate = /* @__PURE__ */ ((GraphqlMiddlewareTemplate2) => {
2
+ GraphqlMiddlewareTemplate2["OperationTypes"] = "graphql-operations.d.ts";
3
+ GraphqlMiddlewareTemplate2["ComposableContext"] = "nuxt-graphql-middleware.d.ts";
4
+ GraphqlMiddlewareTemplate2["Documents"] = "graphql-documents.mjs";
5
+ return GraphqlMiddlewareTemplate2;
6
+ })(GraphqlMiddlewareTemplate || {});
7
+ export var GraphqlMiddlewareOperation = /* @__PURE__ */ ((GraphqlMiddlewareOperation2) => {
8
+ GraphqlMiddlewareOperation2["Query"] = "query";
9
+ GraphqlMiddlewareOperation2["Mutation"] = "mutation";
10
+ return GraphqlMiddlewareOperation2;
11
+ })(GraphqlMiddlewareOperation || {});
package/dist/types.d.ts CHANGED
@@ -8,4 +8,4 @@ declare module '@nuxt/schema' {
8
8
  }
9
9
 
10
10
 
11
- export { default } from './module'
11
+ export { ModuleHooks, ModuleOptions, default } from './module'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nuxt-graphql-middleware",
3
- "version": "3.0.0-beta.2",
3
+ "version": "3.0.0-beta.4",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -16,34 +16,51 @@
16
16
  ],
17
17
  "scripts": {
18
18
  "prepack": "nuxt-module-build",
19
- "dev": "nuxi dev playground",
19
+ "dev": "nuxi dev playground --trace-warnings",
20
20
  "dev:build": "nuxi build playground",
21
21
  "dev:prepare": "nuxt-module-build --stub && nuxi prepare playground",
22
22
  "typedoc": "typedoc --plugin typedoc-plugin-markdown --out foobar",
23
23
  "docs:dev": "vitepress dev docs --port 5000",
24
24
  "docs:build": "vitepress build docs",
25
- "docs:serve": "vitepress serve docs --port 5000"
25
+ "docs:serve": "vitepress serve docs --port 5000",
26
+ "cypress": "cypress run --e2e",
27
+ "cypress:open": "cypress open --e2e",
28
+ "test": "vitest",
29
+ "test:ci": "vitest run",
30
+ "test:coverage": "vitest run --coverage"
26
31
  },
27
32
  "dependencies": {
28
- "@graphql-codegen/cli": "^2.11.8",
33
+ "@graphql-codegen/cli": "^2.15.0",
29
34
  "@graphql-codegen/schema-ast": "^2.5.1",
30
- "@graphql-codegen/typescript": "^2.7.3",
31
- "@graphql-codegen/typescript-generic-sdk": "^3.0.1",
32
- "@graphql-codegen/typescript-operations": "^2.5.3",
35
+ "@graphql-codegen/typescript": "^2.8.3",
36
+ "@graphql-codegen/typescript-generic-sdk": "^3.0.4",
37
+ "@graphql-codegen/typescript-operations": "^2.5.8",
33
38
  "@graphql-fragment-import/lib": "^2.0.0",
34
- "@nuxt/kit": "^3.0.0-rc.8"
39
+ "@graphql-tools/utils": "^9.1.1",
40
+ "@nuxt/kit": "^3.0.0",
41
+ "cli-table": "^0.3.11",
42
+ "inquirer": "^9.1.4"
35
43
  },
36
44
  "devDependencies": {
37
- "@nuxt/module-builder": "latest",
38
- "@nuxtjs/eslint-config-typescript": "latest",
39
- "eslint": "latest",
45
+ "@nuxt/module-builder": "^0.2.1",
46
+ "@nuxt/schema": "^3.0.0",
47
+ "@nuxt/test-utils": "^3.0.0",
48
+ "@nuxtjs/eslint-config-typescript": "^12.0.0",
49
+ "@types/capture-console": "^1.0.1",
50
+ "@types/cli-table": "^0.3.1",
51
+ "@types/inquirer": "^9.0.3",
52
+ "@vitest/coverage-c8": "^0.25.3",
53
+ "cypress": "^11.2.0",
54
+ "eslint": "^8.29.0",
40
55
  "eslint-config-prettier": "^8.5.0",
41
56
  "eslint-plugin-prettier": "^4.2.1",
42
- "jsdoc-to-markdown": "^7.1.1",
43
- "nuxt": "^3.0.0-rc.8",
44
- "prettier": "^2.7.1",
45
- "typedoc": "^0.23.14",
46
- "typedoc-plugin-markdown": "^3.13.5",
47
- "vitepress": "^1.0.0-alpha.13"
57
+ "jsdoc-to-markdown": "^8.0.0",
58
+ "nuxt": "^3.0.0",
59
+ "prettier": "^2.8.0",
60
+ "strip-ansi": "^7.0.1",
61
+ "typedoc": "^0.23.21",
62
+ "typedoc-plugin-markdown": "^3.14.0",
63
+ "vitepress": "^1.0.0-alpha.29",
64
+ "vitest": "^0.25.3"
48
65
  }
49
66
  }
@@ -1,2 +0,0 @@
1
- declare const _default: any;
2
- export default _default;
@@ -1,9 +0,0 @@
1
- import { ref, useNuxtApp, defineNuxtPlugin } from "#imports";
2
- export default defineNuxtPlugin(() => {
3
- const nuxtApp = useNuxtApp();
4
- if (!nuxtApp?._graphql_middleware) {
5
- nuxtApp._graphql_middleware = ref({
6
- fetchOptions: {}
7
- });
8
- }
9
- });