@webiny/handler-graphql 6.5.1 → 6.5.2-beta.1

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.
@@ -5,6 +5,7 @@ import { createGraphQLSchema, getSchemaPlugins } from "./createGraphQLSchema.js"
5
5
  import debugPlugins from "./debugPlugins.js";
6
6
  import { processRequestBody } from "./processRequestBody.js";
7
7
  import { createRequestBody } from "./createRequestBody.js";
8
+ import { isJsonContentType, replyInvalidRequestBody, replyUnsupportedMediaType } from "./jsonContentType.js";
8
9
  const DEFAULT_CACHE_MAX_AGE = 30758400;
9
10
  const createCacheKey = (context)=>{
10
11
  const plugins = getSchemaPlugins(context);
@@ -39,6 +40,7 @@ const createGraphQLHandler = (options = {})=>{
39
40
  "Cache-Control": `public, max-age=${DEFAULT_CACHE_MAX_AGE}`
40
41
  }).send({}).hijack());
41
42
  onPost(path, async (request, reply)=>{
43
+ if (!isJsonContentType(request)) return replyUnsupportedMediaType(reply);
42
44
  const contextCacheKey = createCacheKey(context);
43
45
  if (!schema || cacheKey !== contextCacheKey) try {
44
46
  schema = await createGraphQLSchema(context);
@@ -52,6 +54,8 @@ const createGraphQLHandler = (options = {})=>{
52
54
  } catch (ex) {
53
55
  console.error("Error while creating the body request.");
54
56
  console.error(formatErrorPayload(ex));
57
+ const invalidRequestReply = replyInvalidRequestBody(reply, ex);
58
+ if (invalidRequestReply) return invalidRequestReply;
55
59
  throw ex;
56
60
  }
57
61
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"createGraphQLHandler.js","sources":["../src/createGraphQLHandler.ts"],"sourcesContent":["import { toBoolean } from \"@webiny/stdlib\";\nimport type { GraphQLSchema } from \"graphql\";\nimport type { Context } from \"@webiny/handler\";\nimport { RoutePlugin } from \"@webiny/handler\";\nimport WebinyError from \"@webiny/error\";\nimport type { Plugin } from \"@webiny/plugins/types.js\";\nimport type { GraphQLRequestBody, HandlerGraphQLOptions } from \"./types.js\";\nimport { createGraphQLSchema, getSchemaPlugins } from \"./createGraphQLSchema.js\";\nimport debugPlugins from \"./debugPlugins.js\";\nimport { processRequestBody } from \"./processRequestBody.js\";\nimport { createRequestBody } from \"~/createRequestBody.js\";\n\nconst DEFAULT_CACHE_MAX_AGE = 30758400; // 1 year\n\nconst createCacheKey = (context: Context) => {\n const plugins = getSchemaPlugins(context);\n // TODO: in the near future, we have to assign a fixed name to every\n // TODO: GraphQLSchema plugin, to be able to create a reliable cache key.\n\n // TODO: `getCurrentTenant` should be injected as a parameter.\n // @ts-expect-error TODO: We should not be accessing `context` like this here.\n const tenant = context.tenancy?.getCurrentTenant();\n\n return [tenant ? `tenant:${tenant.id}` : null, plugins.length.toString()]\n .filter(Boolean)\n .join(\"#\");\n};\n\nconst formatErrorPayload = (error: Error): string => {\n if (error instanceof WebinyError) {\n return JSON.stringify({\n type: \"CoreGraphQLWebinyError\",\n message: error.message,\n code: error.code,\n data: error.data,\n stack: error.stack\n });\n }\n\n return JSON.stringify({\n type: \"Error\",\n name: error.name,\n message: error.message,\n stack: error.stack\n });\n};\n\nexport default (options: HandlerGraphQLOptions = {}): Plugin[] => {\n let schema: GraphQLSchema | undefined = undefined;\n let cacheKey: string | undefined = undefined;\n\n const debug = toBoolean(options.debug);\n\n const path = options?.path || \"/graphql\";\n\n const route = new RoutePlugin(async ({ onPost, onOptions, context }) => {\n onOptions(path, async (_, reply) => {\n return reply\n .status(204)\n .headers({\n \"Cache-Control\": `public, max-age=${DEFAULT_CACHE_MAX_AGE}`\n })\n .send({})\n .hijack();\n });\n onPost(path, async (request, reply) => {\n const contextCacheKey = createCacheKey(context as Context);\n if (!schema || cacheKey !== contextCacheKey) {\n try {\n schema = await createGraphQLSchema(context);\n cacheKey = contextCacheKey;\n } catch (ex) {\n return reply.code(500).send(formatErrorPayload(ex));\n }\n }\n let body: GraphQLRequestBody | GraphQLRequestBody[];\n try {\n body = createRequestBody(request.body);\n } catch (ex) {\n console.error(`Error while creating the body request.`);\n console.error(formatErrorPayload(ex));\n throw ex;\n }\n try {\n const result = await processRequestBody(body, schema, context);\n /**\n * IMPORTANT! Do not send anything if reply was already sent.\n */\n if (reply.sent) {\n console.warn(\"Reply already sent, cannot send the result (handler-graphql).\");\n return reply;\n }\n return reply.status(200).send(result);\n } catch (ex) {\n console.error(`Error while processing the body request.`);\n console.error(formatErrorPayload(ex));\n throw ex;\n }\n });\n });\n\n route.name = \"handler.graphql.route.default\";\n\n return [\n ...(debug ? debugPlugins() : []),\n {\n type: \"wcp-telemetry-tracker\"\n },\n route\n ];\n};\n"],"names":["DEFAULT_CACHE_MAX_AGE","createCacheKey","context","plugins","getSchemaPlugins","tenant","Boolean","formatErrorPayload","error","WebinyError","JSON","options","schema","cacheKey","debug","toBoolean","path","route","RoutePlugin","onPost","onOptions","_","reply","request","contextCacheKey","createGraphQLSchema","ex","body","createRequestBody","console","result","processRequestBody","debugPlugins"],"mappings":";;;;;;;AAYA,MAAMA,wBAAwB;AAE9B,MAAMC,iBAAiB,CAACC;IACpB,MAAMC,UAAUC,iBAAiBF;IAMjC,MAAMG,SAASH,QAAQ,OAAO,EAAE;IAEhC,OAAO;QAACG,SAAS,CAAC,OAAO,EAAEA,OAAO,EAAE,EAAE,GAAG;QAAMF,QAAQ,MAAM,CAAC,QAAQ;KAAG,CACpE,MAAM,CAACG,SACP,IAAI,CAAC;AACd;AAEA,MAAMC,qBAAqB,CAACC;IACxB,IAAIA,iBAAiBC,eACjB,OAAOC,KAAK,SAAS,CAAC;QAClB,MAAM;QACN,SAASF,MAAM,OAAO;QACtB,MAAMA,MAAM,IAAI;QAChB,MAAMA,MAAM,IAAI;QAChB,OAAOA,MAAM,KAAK;IACtB;IAGJ,OAAOE,KAAK,SAAS,CAAC;QAClB,MAAM;QACN,MAAMF,MAAM,IAAI;QAChB,SAASA,MAAM,OAAO;QACtB,OAAOA,MAAM,KAAK;IACtB;AACJ;AAEA,6BAAgB,CAAAG,UAAiC,CAAC,CAAC;IAC/C,IAAIC;IACJ,IAAIC;IAE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esContent":["import { toBoolean } from \"@webiny/stdlib\";\nimport type { GraphQLSchema } from \"graphql\";\nimport type { Context } from \"@webiny/handler\";\nimport { RoutePlugin } from \"@webiny/handler\";\nimport WebinyError from \"@webiny/error\";\nimport type { Plugin } from \"@webiny/plugins/types.js\";\nimport type { GraphQLRequestBody, HandlerGraphQLOptions } from \"./types.js\";\nimport { createGraphQLSchema, getSchemaPlugins } from \"./createGraphQLSchema.js\";\nimport debugPlugins from \"./debugPlugins.js\";\nimport { processRequestBody } from \"./processRequestBody.js\";\nimport { createRequestBody } from \"~/createRequestBody.js\";\nimport {\n isJsonContentType,\n replyInvalidRequestBody,\n replyUnsupportedMediaType\n} from \"~/jsonContentType.js\";\n\nconst DEFAULT_CACHE_MAX_AGE = 30758400; // 1 year\n\nconst createCacheKey = (context: Context) => {\n const plugins = getSchemaPlugins(context);\n // TODO: in the near future, we have to assign a fixed name to every\n // TODO: GraphQLSchema plugin, to be able to create a reliable cache key.\n\n // TODO: `getCurrentTenant` should be injected as a parameter.\n // @ts-expect-error TODO: We should not be accessing `context` like this here.\n const tenant = context.tenancy?.getCurrentTenant();\n\n return [tenant ? `tenant:${tenant.id}` : null, plugins.length.toString()]\n .filter(Boolean)\n .join(\"#\");\n};\n\nconst formatErrorPayload = (error: Error): string => {\n if (error instanceof WebinyError) {\n return JSON.stringify({\n type: \"CoreGraphQLWebinyError\",\n message: error.message,\n code: error.code,\n data: error.data,\n stack: error.stack\n });\n }\n\n return JSON.stringify({\n type: \"Error\",\n name: error.name,\n message: error.message,\n stack: error.stack\n });\n};\n\nexport default (options: HandlerGraphQLOptions = {}): Plugin[] => {\n let schema: GraphQLSchema | undefined = undefined;\n let cacheKey: string | undefined = undefined;\n\n const debug = toBoolean(options.debug);\n\n const path = options?.path || \"/graphql\";\n\n const route = new RoutePlugin(async ({ onPost, onOptions, context }) => {\n onOptions(path, async (_, reply) => {\n return reply\n .status(204)\n .headers({\n \"Cache-Control\": `public, max-age=${DEFAULT_CACHE_MAX_AGE}`\n })\n .send({})\n .hijack();\n });\n onPost(path, async (request, reply) => {\n if (!isJsonContentType(request)) {\n return replyUnsupportedMediaType(reply);\n }\n const contextCacheKey = createCacheKey(context as Context);\n if (!schema || cacheKey !== contextCacheKey) {\n try {\n schema = await createGraphQLSchema(context);\n cacheKey = contextCacheKey;\n } catch (ex) {\n return reply.code(500).send(formatErrorPayload(ex));\n }\n }\n let body: GraphQLRequestBody | GraphQLRequestBody[];\n try {\n body = createRequestBody(request.body);\n } catch (ex) {\n console.error(`Error while creating the body request.`);\n console.error(formatErrorPayload(ex));\n const invalidRequestReply = replyInvalidRequestBody(reply, ex);\n if (invalidRequestReply) {\n return invalidRequestReply;\n }\n throw ex;\n }\n try {\n const result = await processRequestBody(body, schema, context);\n /**\n * IMPORTANT! Do not send anything if reply was already sent.\n */\n if (reply.sent) {\n console.warn(\"Reply already sent, cannot send the result (handler-graphql).\");\n return reply;\n }\n return reply.status(200).send(result);\n } catch (ex) {\n console.error(`Error while processing the body request.`);\n console.error(formatErrorPayload(ex));\n throw ex;\n }\n });\n });\n\n route.name = \"handler.graphql.route.default\";\n\n return [\n ...(debug ? debugPlugins() : []),\n {\n type: \"wcp-telemetry-tracker\"\n },\n route\n ];\n};\n"],"names":["DEFAULT_CACHE_MAX_AGE","createCacheKey","context","plugins","getSchemaPlugins","tenant","Boolean","formatErrorPayload","error","WebinyError","JSON","options","schema","cacheKey","debug","toBoolean","path","route","RoutePlugin","onPost","onOptions","_","reply","request","isJsonContentType","replyUnsupportedMediaType","contextCacheKey","createGraphQLSchema","ex","body","createRequestBody","console","invalidRequestReply","replyInvalidRequestBody","result","processRequestBody","debugPlugins"],"mappings":";;;;;;;;AAiBA,MAAMA,wBAAwB;AAE9B,MAAMC,iBAAiB,CAACC;IACpB,MAAMC,UAAUC,iBAAiBF;IAMjC,MAAMG,SAASH,QAAQ,OAAO,EAAE;IAEhC,OAAO;QAACG,SAAS,CAAC,OAAO,EAAEA,OAAO,EAAE,EAAE,GAAG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,KAAK,CAACxB,mBAAmBqB;gBACjC,MAAMI,sBAAsBC,wBAAwBX,OAAOM;gBAC3D,IAAII,qBACA,OAAOA;gBAEX,MAAMJ;YACV;YACA,IAAI;gBACA,MAAMM,SAAS,MAAMC,mBAAmBN,MAAMjB,QAAQV;gBAItD,IAAIoB,MAAM,IAAI,EAAE;oBACZS,QAAQ,IAAI,CAAC;oBACb,OAAOT;gBACX;gBACA,OAAOA,MAAM,MAAM,CAAC,KAAK,IAAI,CAACY;YAClC,EAAE,OAAON,IAAI;gBACTG,QAAQ,KAAK,CAAC;gBACdA,QAAQ,KAAK,CAACxB,mBAAmBqB;gBACjC,MAAMA;YACV;QACJ;IACJ;IAEAX,MAAM,IAAI,GAAG;IAEb,OAAO;WACCH,QAAQsB,iBAAiB,EAAE;QAC/B;YACI,MAAM;QACV;QACAnB;KACH;AACL"}
@@ -1,4 +1,5 @@
1
1
  import zod from "zod";
2
+ import { parseJson } from "@webiny/utils/parseJson.js";
2
3
  import { WebinyError } from "@webiny/error";
3
4
  import { createZodError } from "@webiny/utils/createZodError.js";
4
5
  const requestBodySchema = zod.looseObject({
@@ -10,16 +11,27 @@ const schema = zod.union([
10
11
  requestBodySchema,
11
12
  zod.array(requestBodySchema)
12
13
  ]);
14
+ const invalidRequestError = (data)=>new WebinyError({
15
+ message: "Invalid GraphQL request! Check your query and variables.",
16
+ code: "GRAPHQL_REQUEST_INVALID",
17
+ data
18
+ });
19
+ const parseBody = (input)=>{
20
+ if ("string" != typeof input) return input;
21
+ try {
22
+ return parseJson(input);
23
+ } catch (ex) {
24
+ throw invalidRequestError({
25
+ reason: ex.message
26
+ });
27
+ }
28
+ };
13
29
  const createRequestBody = (input)=>{
14
- const body = "string" == typeof input ? JSON.parse(input) : input;
30
+ const body = parseBody(input);
15
31
  const result = schema.safeParse(body);
16
32
  if (!result.success) {
17
33
  const error = createZodError(result.error);
18
- throw new WebinyError({
19
- message: "Invalid GraphQL request! Check your query and variables.",
20
- code: "GRAPHQL_REQUEST_INVALID",
21
- data: error.data
22
- });
34
+ throw invalidRequestError(error.data);
23
35
  }
24
36
  return result.data;
25
37
  };
@@ -1 +1 @@
1
- {"version":3,"file":"createRequestBody.js","sources":["../src/createRequestBody.ts"],"sourcesContent":["import zod from \"zod\";\nimport { WebinyError } from \"@webiny/error\";\nimport { createZodError } from \"@webiny/utils/createZodError.js\";\nimport type { GraphQLRequestBody } from \"~/types.js\";\n\nconst requestBodySchema = zod.looseObject({\n query: zod.string(),\n variables: zod.record(zod.string(), zod.any()).nullish().optional(),\n operationName: zod\n .string()\n .nullish()\n .optional()\n .transform(value => {\n return value || undefined;\n })\n});\n\nconst schema = zod.union([requestBodySchema, zod.array(requestBodySchema)]);\n\nexport const createRequestBody = (input: unknown): GraphQLRequestBody | GraphQLRequestBody[] => {\n const body = typeof input === \"string\" ? JSON.parse(input) : input;\n\n const result = schema.safeParse(body);\n if (!result.success) {\n const error = createZodError(result.error);\n throw new WebinyError({\n message: \"Invalid GraphQL request! Check your query and variables.\",\n code: \"GRAPHQL_REQUEST_INVALID\",\n data: error.data\n });\n }\n return result.data;\n};\n"],"names":["requestBodySchema","zod","value","undefined","schema","createRequestBody","input","body","JSON","result","error","createZodError","WebinyError"],"mappings":";;;AAKA,MAAMA,oBAAoBC,IAAI,WAAW,CAAC;IACtC,OAAOA,IAAI,MAAM;IACjB,WAAWA,IAAI,MAAM,CAACA,IAAI,MAAM,IAAIA,IAAI,GAAG,IAAI,OAAO,GAAG,QAAQ;IACjE,eAAeA,IAAAA,MACJ,GACN,OAAO,GACP,QAAQ,GACR,SAAS,CAACC,CAAAA,QACAA,SAASC;AAE5B;AAEA,MAAMC,SAASH,IAAI,KAAK,CAAC;IAACD;IAAmBC,IAAI,KAAK,CAACD;CAAmB;AAEnE,MAAMK,oBAAoB,CAACC;IAC9B,MAAMC,OAAO,AAAiB,YAAjB,OAAOD,QAAqBE,KAAK,KAAK,CAACF,SAASA;IAE7D,MAAMG,SAASL,OAAO,SAAS,CAACG;IAChC,IAAI,CAACE,OAAO,OAAO,EAAE;QACjB,MAAMC,QAAQC,eAAeF,OAAO,KAAK;QACzC,MAAM,IAAIG,YAAY;YAClB,SAAS;YACT,MAAM;YACN,MAAMF,MAAM,IAAI;QACpB;IACJ;IACA,OAAOD,OAAO,IAAI;AACtB"}
1
+ {"version":3,"file":"createRequestBody.js","sources":["../src/createRequestBody.ts"],"sourcesContent":["import zod from \"zod\";\nimport { parseJson } from \"@webiny/utils/parseJson.js\";\nimport { WebinyError } from \"@webiny/error\";\nimport { createZodError } from \"@webiny/utils/createZodError.js\";\nimport type { GraphQLRequestBody } from \"~/types.js\";\n\nconst requestBodySchema = zod.looseObject({\n query: zod.string(),\n variables: zod.record(zod.string(), zod.any()).nullish().optional(),\n operationName: zod\n .string()\n .nullish()\n .optional()\n .transform(value => {\n return value || undefined;\n })\n});\n\nconst schema = zod.union([requestBodySchema, zod.array(requestBodySchema)]);\n\nconst invalidRequestError = (data?: Record<string, unknown> | null) => {\n return new WebinyError({\n message: \"Invalid GraphQL request! Check your query and variables.\",\n code: \"GRAPHQL_REQUEST_INVALID\",\n data\n });\n};\n\n/**\n * String bodies (e.g. sent as `text/plain`) are parsed with `parseJson`,\n * which rejects `__proto__` and `constructor.prototype` keys.\n */\nconst parseBody = (input: unknown): unknown => {\n if (typeof input !== \"string\") {\n return input;\n }\n try {\n return parseJson(input);\n } catch (ex) {\n throw invalidRequestError({ reason: (ex as Error).message });\n }\n};\n\nexport const createRequestBody = (input: unknown): GraphQLRequestBody | GraphQLRequestBody[] => {\n const body = parseBody(input);\n\n const result = schema.safeParse(body);\n if (!result.success) {\n const error = createZodError(result.error);\n throw invalidRequestError(error.data);\n }\n return result.data;\n};\n"],"names":["requestBodySchema","zod","value","undefined","schema","invalidRequestError","data","WebinyError","parseBody","input","parseJson","ex","createRequestBody","body","result","error","createZodError"],"mappings":";;;;AAMA,MAAMA,oBAAoBC,IAAI,WAAW,CAAC;IACtC,OAAOA,IAAI,MAAM;IACjB,WAAWA,IAAI,MAAM,CAACA,IAAI,MAAM,IAAIA,IAAI,GAAG,IAAI,OAAO,GAAG,QAAQ;IACjE,eAAeA,IAAAA,MACJ,GACN,OAAO,GACP,QAAQ,GACR,SAAS,CAACC,CAAAA,QACAA,SAASC;AAE5B;AAEA,MAAMC,SAASH,IAAI,KAAK,CAAC;IAACD;IAAmBC,IAAI,KAAK,CAACD;CAAmB;AAE1E,MAAMK,sBAAsB,CAACC,OAClB,IAAIC,YAAY;QACnB,SAAS;QACT,MAAM;QACND;IACJ;AAOJ,MAAME,YAAY,CAACC;IACf,IAAI,AAAiB,YAAjB,OAAOA,OACP,OAAOA;IAEX,IAAI;QACA,OAAOC,UAAUD;IACrB,EAAE,OAAOE,IAAI;QACT,MAAMN,oBAAoB;YAAE,QAASM,GAAa,OAAO;QAAC;IAC9D;AACJ;AAEO,MAAMC,oBAAoB,CAACH;IAC9B,MAAMI,OAAOL,UAAUC;IAEvB,MAAMK,SAASV,OAAO,SAAS,CAACS;IAChC,IAAI,CAACC,OAAO,OAAO,EAAE;QACjB,MAAMC,QAAQC,eAAeF,OAAO,KAAK;QACzC,MAAMT,oBAAoBU,MAAM,IAAI;IACxC;IACA,OAAOD,OAAO,IAAI;AACtB"}
@@ -7,9 +7,21 @@ export interface IGraphQLSchema {
7
7
  }
8
8
  /** Define custom GraphQL schema extensions. */
9
9
  export interface IGraphQLSchemaFactory {
10
+ /**
11
+ * Runs once per cached schema, not once per request. Resolvers added here must get request-scoped
12
+ * services through `addResolver({ dependencies })`, never from `this`.
13
+ */
10
14
  execute(builder: GraphQLSchemaBuilder.Interface): Promise<GraphQLSchemaBuilder.Interface>;
11
15
  }
12
- /** Define custom GraphQL schema extensions. */
16
+ /**
17
+ * Define custom GraphQL schema extensions.
18
+ *
19
+ * The built schema is cached across requests. Constructor dependencies are injected only for the
20
+ * request that builds it, so a resolver must never read them (`this.identityContext` and similar):
21
+ * every later request would run with that request's identity, tenant and use cases. Declare what a
22
+ * resolver needs in `builder.addResolver({ dependencies })`, which resolves it from the current
23
+ * request, and register the factory with `dependencies: []`.
24
+ */
13
25
  export declare const GraphQLSchemaFactory: import("@webiny/di").Abstraction<IGraphQLSchemaFactory>;
14
26
  export declare namespace GraphQLSchemaFactory {
15
27
  type Interface = IGraphQLSchemaFactory;
@@ -1 +1 @@
1
- {"version":3,"file":"graphql/abstractions.public.js","sources":["../../src/graphql/abstractions.public.ts"],"sourcesContent":["/**\n * This file contains abstraction for use by third party developers.\n */\nimport { createAbstraction } from \"@webiny/feature/api\";\nimport type {\n Resolvers as IResolvers,\n TypeDefs as ITypeDefs,\n ResolverDecorators as IResolverDecorators\n} from \"~/types.js\";\nimport type { GraphQLSchemaBuilder } from \"~/features/GraphQLSchemaBuilder/abstractions.js\";\n\nexport interface IGraphQLSchema {\n typeDefs?: ITypeDefs;\n resolvers?: IResolvers<any>;\n resolverDecorators?: IResolverDecorators;\n}\n\n/** Define custom GraphQL schema extensions. */\nexport interface IGraphQLSchemaFactory {\n execute(builder: GraphQLSchemaBuilder.Interface): Promise<GraphQLSchemaBuilder.Interface>;\n}\n\n/** Define custom GraphQL schema extensions. */\nexport const GraphQLSchemaFactory =\n createAbstraction<IGraphQLSchemaFactory>(\"GraphQLSchemaFactory\");\n\nexport namespace GraphQLSchemaFactory {\n export type Interface = IGraphQLSchemaFactory;\n export type SchemaBuilder = GraphQLSchemaBuilder.Interface;\n export type Return = Promise<GraphQLSchemaBuilder.Interface>;\n}\n"],"names":["GraphQLSchemaFactory","createAbstraction"],"mappings":";AAuBO,MAAMA,uBACTC,kBAAyC"}
1
+ {"version":3,"file":"graphql/abstractions.public.js","sources":["../../src/graphql/abstractions.public.ts"],"sourcesContent":["/**\n * This file contains abstraction for use by third party developers.\n */\nimport { createAbstraction } from \"@webiny/feature/api\";\nimport type {\n Resolvers as IResolvers,\n TypeDefs as ITypeDefs,\n ResolverDecorators as IResolverDecorators\n} from \"~/types.js\";\nimport type { GraphQLSchemaBuilder } from \"~/features/GraphQLSchemaBuilder/abstractions.js\";\n\nexport interface IGraphQLSchema {\n typeDefs?: ITypeDefs;\n resolvers?: IResolvers<any>;\n resolverDecorators?: IResolverDecorators;\n}\n\n/** Define custom GraphQL schema extensions. */\nexport interface IGraphQLSchemaFactory {\n /**\n * Runs once per cached schema, not once per request. Resolvers added here must get request-scoped\n * services through `addResolver({ dependencies })`, never from `this`.\n */\n execute(builder: GraphQLSchemaBuilder.Interface): Promise<GraphQLSchemaBuilder.Interface>;\n}\n\n/**\n * Define custom GraphQL schema extensions.\n *\n * The built schema is cached across requests. Constructor dependencies are injected only for the\n * request that builds it, so a resolver must never read them (`this.identityContext` and similar):\n * every later request would run with that request's identity, tenant and use cases. Declare what a\n * resolver needs in `builder.addResolver({ dependencies })`, which resolves it from the current\n * request, and register the factory with `dependencies: []`.\n */\nexport const GraphQLSchemaFactory =\n createAbstraction<IGraphQLSchemaFactory>(\"GraphQLSchemaFactory\");\n\nexport namespace GraphQLSchemaFactory {\n export type Interface = IGraphQLSchemaFactory;\n export type SchemaBuilder = GraphQLSchemaBuilder.Interface;\n export type Return = Promise<GraphQLSchemaBuilder.Interface>;\n}\n"],"names":["GraphQLSchemaFactory","createAbstraction"],"mappings":";AAmCO,MAAMA,uBACTC,kBAAyC"}
@@ -0,0 +1,14 @@
1
+ import type { Reply, Request } from "@webiny/handler/types.js";
2
+ export declare const GRAPHQL_UNSUPPORTED_MEDIA_TYPE = "GRAPHQL_UNSUPPORTED_MEDIA_TYPE";
3
+ /**
4
+ * GraphQL requests must be sent as `application/json` (parameters such as `charset` are allowed).
5
+ *
6
+ * Other content types (e.g. `text/plain`, form posts) are "simple" requests that browsers send
7
+ * cross-site without a CORS preflight, so they are refused before the request body is read.
8
+ */
9
+ export declare const isJsonContentType: (request: Pick<Request, "headers">) => boolean;
10
+ export declare const replyUnsupportedMediaType: (reply: Reply) => Reply;
11
+ /**
12
+ * An invalid GraphQL request body (e.g. no `query`) is a client error, so it gets a 400.
13
+ */
14
+ export declare const replyInvalidRequestBody: (reply: Reply, error: unknown) => Reply | null;
@@ -0,0 +1,32 @@
1
+ const GRAPHQL_UNSUPPORTED_MEDIA_TYPE = "GRAPHQL_UNSUPPORTED_MEDIA_TYPE";
2
+ const isJsonContentType = (request)=>{
3
+ const header = request.headers["content-type"];
4
+ const value = Array.isArray(header) ? header[0] : header;
5
+ if (!value) return false;
6
+ const mediaType = value.split(";")[0].trim().toLowerCase();
7
+ return "application/json" === mediaType;
8
+ };
9
+ const replyUnsupportedMediaType = (reply)=>reply.code(415).headers({
10
+ "Cache-Control": "no-store"
11
+ }).send({
12
+ data: null,
13
+ error: {
14
+ message: 'GraphQL requests must be sent with "Content-Type: application/json".',
15
+ code: GRAPHQL_UNSUPPORTED_MEDIA_TYPE,
16
+ data: null
17
+ }
18
+ });
19
+ const replyInvalidRequestBody = (reply, error)=>{
20
+ const ex = error;
21
+ if (ex?.code !== "GRAPHQL_REQUEST_INVALID") return null;
22
+ return reply.code(400).headers({
23
+ "Cache-Control": "no-store"
24
+ }).send({
25
+ message: ex.message,
26
+ code: ex.code,
27
+ data: ex.data ?? null
28
+ });
29
+ };
30
+ export { GRAPHQL_UNSUPPORTED_MEDIA_TYPE, isJsonContentType, replyInvalidRequestBody, replyUnsupportedMediaType };
31
+
32
+ //# sourceMappingURL=jsonContentType.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jsonContentType.js","sources":["../src/jsonContentType.ts"],"sourcesContent":["import type { Reply, Request } from \"@webiny/handler/types.js\";\n\nexport const GRAPHQL_UNSUPPORTED_MEDIA_TYPE = \"GRAPHQL_UNSUPPORTED_MEDIA_TYPE\";\n\n/**\n * GraphQL requests must be sent as `application/json` (parameters such as `charset` are allowed).\n *\n * Other content types (e.g. `text/plain`, form posts) are \"simple\" requests that browsers send\n * cross-site without a CORS preflight, so they are refused before the request body is read.\n */\nexport const isJsonContentType = (request: Pick<Request, \"headers\">): boolean => {\n const header = request.headers[\"content-type\"];\n const value = Array.isArray(header) ? header[0] : header;\n if (!value) {\n return false;\n }\n const mediaType = value.split(\";\")[0].trim().toLowerCase();\n return mediaType === \"application/json\";\n};\n\nexport const replyUnsupportedMediaType = (reply: Reply): Reply => {\n return reply\n .code(415)\n .headers({ \"Cache-Control\": \"no-store\" })\n .send({\n data: null,\n error: {\n message: 'GraphQL requests must be sent with \"Content-Type: application/json\".',\n code: GRAPHQL_UNSUPPORTED_MEDIA_TYPE,\n data: null\n }\n });\n};\n\n/**\n * An invalid GraphQL request body (e.g. no `query`) is a client error, so it gets a 400.\n */\nexport const replyInvalidRequestBody = (reply: Reply, error: unknown): Reply | null => {\n const ex = error as { code?: string; message?: string; data?: unknown };\n if (ex?.code !== \"GRAPHQL_REQUEST_INVALID\") {\n return null;\n }\n return reply\n .code(400)\n .headers({ \"Cache-Control\": \"no-store\" })\n .send({\n message: ex.message,\n code: ex.code,\n data: ex.data ?? null\n });\n};\n"],"names":["GRAPHQL_UNSUPPORTED_MEDIA_TYPE","isJsonContentType","request","header","value","Array","mediaType","replyUnsupportedMediaType","reply","replyInvalidRequestBody","error","ex"],"mappings":"AAEO,MAAMA,iCAAiC;AAQvC,MAAMC,oBAAoB,CAACC;IAC9B,MAAMC,SAASD,QAAQ,OAAO,CAAC,eAAe;IAC9C,MAAME,QAAQC,MAAM,OAAO,CAACF,UAAUA,MAAM,CAAC,EAAE,GAAGA;IAClD,IAAI,CAACC,OACD,OAAO;IAEX,MAAME,YAAYF,MAAM,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,GAAG,WAAW;IACxD,OAAOE,AAAc,uBAAdA;AACX;AAEO,MAAMC,4BAA4B,CAACC,QAC/BA,MACF,IAAI,CAAC,KACL,OAAO,CAAC;QAAE,iBAAiB;IAAW,GACtC,IAAI,CAAC;QACF,MAAM;QACN,OAAO;YACH,SAAS;YACT,MAAMR;YACN,MAAM;QACV;IACJ;AAMD,MAAMS,0BAA0B,CAACD,OAAcE;IAClD,MAAMC,KAAKD;IACX,IAAIC,IAAI,SAAS,2BACb,OAAO;IAEX,OAAOH,MACF,IAAI,CAAC,KACL,OAAO,CAAC;QAAE,iBAAiB;IAAW,GACtC,IAAI,CAAC;QACF,SAASG,GAAG,OAAO;QACnB,MAAMA,GAAG,IAAI;QACb,MAAMA,GAAG,IAAI,IAAI;IACrB;AACR"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webiny/handler-graphql",
3
- "version": "6.5.1",
3
+ "version": "6.5.2-beta.1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./index.js",
@@ -18,26 +18,26 @@
18
18
  "Adrian Smijulj <adrian@webiny.com>"
19
19
  ],
20
20
  "dependencies": {
21
- "@graphql-tools/merge": "10.0.6",
22
- "@graphql-tools/resolvers-composition": "8.0.6",
23
- "@graphql-tools/schema": "11.0.6",
24
- "@graphql-tools/utils": "13.1.3",
25
- "@webiny/api": "6.5.1",
21
+ "@graphql-tools/merge": "10.0.8",
22
+ "@graphql-tools/resolvers-composition": "8.0.8",
23
+ "@graphql-tools/schema": "11.0.8",
24
+ "@graphql-tools/utils": "13.2.1",
25
+ "@webiny/api": "6.5.2-beta.1",
26
26
  "@webiny/di": "1.1.0",
27
- "@webiny/error": "6.5.1",
28
- "@webiny/feature": "6.5.1",
29
- "@webiny/handler": "6.5.1",
30
- "@webiny/plugins": "6.5.1",
27
+ "@webiny/error": "6.5.2-beta.1",
28
+ "@webiny/feature": "6.5.2-beta.1",
29
+ "@webiny/handler": "6.5.2-beta.1",
30
+ "@webiny/plugins": "6.5.2-beta.1",
31
31
  "@webiny/stdlib": "0.0.20",
32
- "@webiny/utils": "6.5.1",
32
+ "@webiny/utils": "6.5.2-beta.1",
33
33
  "graphql": "16.14.2",
34
34
  "graphql-scalars": "2.0.1",
35
35
  "graphql-tag": "2.12.7",
36
36
  "zod": "4.6.7"
37
37
  },
38
38
  "devDependencies": {
39
- "@webiny/build-tools": "6.5.1",
40
- "@webiny/handler-aws": "6.5.1",
39
+ "@webiny/build-tools": "6.5.2-beta.1",
40
+ "@webiny/handler-aws": "6.5.2-beta.1",
41
41
  "rimraf": "6.1.3",
42
42
  "typescript": "7.0.2",
43
43
  "vitest": "5.0.5"