Skip to content

Commit

Permalink
feat: cors headers on error (#803)
Browse files Browse the repository at this point in the history
<!--
Pull requests are squashed and merged using:
- their title as the commit message
- their description as the commit body

Having a good title and description is important for the users to get
readable changelog.
-->

<!-- 1. Explain WHAT the change is about -->

-

<!-- 2. Explain WHY the change cannot be made simpler -->

-

<!-- 3. Explain HOW users should update their code -->

#### 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
  • Loading branch information
j03-dev authored Aug 5, 2024
1 parent fd612f7 commit 2845190
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 6 deletions.
7 changes: 5 additions & 2 deletions typegate/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
"{}[{}:{}]: {}",
Expand Down Expand Up @@ -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 },
});
}
}
Expand Down
4 changes: 2 additions & 2 deletions typegate/src/services/graphql_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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}`);
Expand Down
4 changes: 2 additions & 2 deletions typegate/src/services/rest_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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}`);
Expand Down

0 comments on commit 2845190

Please sign in to comment.