apollo-server-integrations / apollo-server-integration-h3

An Apollo Server integration for use with h3 and nuxt
MIT License
24 stars 0 forks source link

[Question] How to set the response status code #43

Closed sdr0x07b6 closed 1 year ago

sdr0x07b6 commented 1 year ago

When using startServerAndCreateH3Handler() to handle GraphQL requests, I am not sure how to set the response status code within the resolver. I have tried several patterns and the result is either a 200 OK returned or a server error.

// 1. 200 OK is returned
setResponseStatus(context.event, 400);
throw new Error('Error message');

// 2. 200 OK is returned
throw createError({
  statusCode: 400,
  statusMessage: 'Error message',
});

// 3. 400 is returned but a server error occurs
// [nuxt] [request error] [unhandled] [500] Cannot set headers after they are sent to the client
context.event.res.statusCode = 400;
context.event.res.end('Error message');

// 4. 400 is returned but a server error occurs
return sendError(context.event, createError({
  statusCode: 400,
  statusMessage: 'Error message',
}));
@as-integrations/h3 v1.1.6

% npx nuxt info
------------------------------
- Operating System: Darwin
- Node Version:     v18.14.2
- Nuxt Version:     3.7.1
- CLI Version:      3.8.0
- Nitro Version:    2.6.3
- Package Manager:  yarn@1.22.19
- Builder:          -
- User Config:      devtools, rootDir
- Runtime Modules:  -
- Build Modules:    -
------------------------------
tobiasdiez commented 1 year ago

Does https://www.apollographql.com/docs/apollo-server/data/errors/#setting-http-status-code-and-headers help?

sdr0x07b6 commented 1 year ago

I was able to achieve my goal with the exact sample code on the page you showed me! I see, I should refer to the apollo docs. I will look at this from now on. Thanks for letting me know.