From 2845190aee34dd0c5556b92f2c0c6677273416d6 Mon Sep 17 00:00:00 2001 From: FITAHIANA Nomeniavo joe <24nomeniavo@gmail.com> Date: Mon, 5 Aug 2024 22:39:35 +0300 Subject: [PATCH] feat: cors headers on error (#803) - - #### Migration notes ... - [ ] The change comes with new or modified tests - [ ] Hard-to-understand functions have explanatory comments - [ ] End-user documentation is updated to reflect the change --- typegate/src/errors.ts | 7 +++++-- typegate/src/services/graphql_service.ts | 4 ++-- typegate/src/services/rest_service.ts | 4 ++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/typegate/src/errors.ts b/typegate/src/errors.ts index 4dd75cb351..a123bdde49 100644 --- a/typegate/src/errors.ts +++ b/typegate/src/errors.ts @@ -55,7 +55,10 @@ export class BaseError extends Error { return this; } - toResponse(graphqlFormat = true): Response { + toResponse( + headers: Headers = new Headers(), + graphqlFormat = true, + ): Response { const type = this.#type ?? this.constructor.name; logger.error( "{}[{}:{}]: {}", @@ -98,7 +101,7 @@ export class BaseError extends Error { return new Response(JSON.stringify(responseObj), { status: this.code, - headers: { "Content-Type": "application/json" }, + headers: { "Content-Type": "application/json", ...headers }, }); } } diff --git a/typegate/src/services/graphql_service.ts b/typegate/src/services/graphql_service.ts index 300c1aebcc..6ccecefd44 100644 --- a/typegate/src/services/graphql_service.ts +++ b/typegate/src/services/graphql_service.ts @@ -51,7 +51,7 @@ export async function handleGraphQL( content = await parseRequest(request); } catch (e) { if (e instanceof BaseError) { - return e.toResponse(); + return e.toResponse(headers); } return badRequest(e.message); } @@ -120,7 +120,7 @@ export async function handleGraphQL( } catch (e) { // throw e; if (e instanceof BaseError) { - return e.toResponse(); + return e.toResponse(headers); } if (e instanceof ResolverError) { logger.error(`field err: ${e.message}`); diff --git a/typegate/src/services/rest_service.ts b/typegate/src/services/rest_service.ts index 848758e3b5..5af00a217b 100644 --- a/typegate/src/services/rest_service.ts +++ b/typegate/src/services/rest_service.ts @@ -65,7 +65,7 @@ export async function handleRest( `query not found: ${name}`, 404, ).withType("NotFound") - .toResponse(false); + .toResponse(headers, false); } const variables = req.method === "GET" @@ -92,7 +92,7 @@ export async function handleRest( } catch (e) { headers.set("Content-Type", "application/json"); if (e instanceof BaseError) { - return e.toResponse(false); + return e.toResponse(headers, false); } if (e instanceof ResolverError) { logger.error(`field err: ${e.message}`);